-1

I am trying to make a program which will show all the teams that have more wins than losses. This is what I have tried so far but I get an error:

File "C:/Users/ACER/Desktop/sfgthg.py", line 9, in g=[c[0] for c in d.items() if c[1]>c[0]]

TypeError: '>' not supported between instances of 'list' and 'str'

d={}
while True:
    x=input("name of the team?(type stop if you want to stop")
    if x=="stop":
        break
    y=int(input("how many losses?"))
    z=int(input("how many wins?"))
    d[x]=[y,z]
g=[c[0] for c in d.items() if c[1]>c[0]]
print(g)
astudent
  • 15
  • 5
  • eval is dangerous! – zamir Dec 30 '19 at 19:15
  • Why do you use `eval` on `input`? You should be using `int(input(...))` – Sunny Patel Dec 30 '19 at 19:17
  • Replace `g=[c[0] for c in d.items() if c[1]>c[0]]` with `g=[key for key,value in d.items() if value[1]>value[0]]`. – Ajay Dabas Dec 30 '19 at 19:23
  • @Sunny Patel thank you for responding! i changed it now! we were taught in school to write with eval – astudent Dec 30 '19 at 19:25
  • For more information, refer [How to iterate over dictionary in python](https://www.geeksforgeeks.org/iterate-over-a-dictionary-in-python/) – Ajay Dabas Dec 30 '19 at 19:25
  • @AjayDabas thank you SO much!! it works :) – astudent Dec 30 '19 at 19:27
  • [`eval` is very dangerous first and foremost](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice). You don't want someone typing in `os.getcwd()` to get the working directory of your code, or (a lot worse](http://vipulchaskar.blogspot.com/2012/10/exploiting-eval-function-in-python.html)! – Sunny Patel Dec 30 '19 at 19:29

3 Answers3

0

When you iterate through the dictionary d, you should be using d.values(), because d.items() returns key-value pairs.

g=[c[0] for c in d.values() if c[1]>c[0]]

Or even better, you can capture like this:

g = filter(lambda c: c[1] > c[0], d)

and g will be a dictionary of winners.

Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
0

As others have mentioned, using eval can be dangerous. Also, you can use dict.values() to directly access the values, but I am assuming you want to create a new dictionary, so I will use dict.items() so that you can get the whole dict entry.

Anyways, this should work for the actual question you are asking:

g = [c for c in d.items() if c[1][0] > c[1][1]]

c[0] gives the key of the item, c[1] gives the value, therefore c[1][0] gives the number of wins, and c[1][1] gives the number of losses (assuming your array is structured as [wins, losses].

edit: if you want only team names, change [c for c.....]to[c[0] for c ......]

0

If you want to use dict.items you can catch the key in a separate variable. This will give you a list of the respective team names:

d={'Madrid':[2,1],
   'Barca':[1,2]}
g=[key for key,c in d.items() if c[1]>c[0]]
print(g)
Chris
  • 445
  • 6
  • 11