python dictionaries values and keys

Viewed 72

I've got dictionary called humans. I want to loop through that dictionary and if value is less than 20 print dictionary key.

humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}
4 Answers

Hello John and welcome to Stack Overflow. Your description of the problem is almost a perfect pseudo-code for how you would implement that:

# I've got dictionary called humans. 
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}

for key, value in humans.items():  # I want to loop through that dictionary 
    if value < 20:                 # and if value is less than 20
        print(key)                 # print dictionary key.

Try this:

for k, v in humans.items():
   if v > 20:
      print(k)

Or, a more pythonic way:

print([k for k, v in humans.items() if v > 20])

Try this, using generator expressions:

result = (k for k, v in humans.items() if v > 20)
print(', '.join(result))

I used commas as separators, if you need each item in a different line simply substitute ', ' with '\n'.

Loop over items().

You can use comprehension (no need to use [ ] as it is in parenthesis already):

print(k for k,v in humans.items() if v > 20)

or really loop:

for k,v in humans.items():
    if v > 20:
       print(k)
Related