Henke Henke - 5 months ago 9
Python Question

Dictionary and for-loop

I'm trying to figure out how to create a for loop in a dictionary where I'm suposed to print both age and names above 25.

I've only managed to print the ages above 25 in the loop but only in a list and I'm not sure how to do it in a dictionary.

So basically I want to know how to print out both the names and ages above 25.

I'm fairly new to python and programming in general and would appreciate some advice and help :)

Answer
names = {"Peter" : 20, "John" : 32, "Ana" : 25, "Mike" : 22, "Connor" : 26, "Chelsea" : 29, "George" : 18, "Helen" : 33}
for name, age in names.iteritems():
    if age > 25:
        print(name+", "+age)

Should do the job. iteritems lets you unwrap all keys and values as a tuple in a loop, it's super useful for these kind of things.

Comments