Say I have a List of dictionaries that have Names and ages and other info, like so:
thisismylist= [
{'Name': 'Albert' , 'Age': 16},
{'Name': 'Suzy', 'Age': 17},
{'Name': 'Johnny', 'Age': 13}
]
How would I go about print the following using a for loop:
Albert
Suzy
Johnny
I just cant wrap my head around this idea...
Get a list of values from a dictionary using List comprehension. Using List comprehension we can get the list of dictionary values. Here we are using a list comprehension to iterate in a dictionary by using an iterator. This will return each value from the key: value pair.
Yes. The values in a dict can be any kind of python object. The keys can be any hashable object (which does not allow a list, but does allow a tuple). Doh!
If you're just looking for values associated with 'Name', your code should look like:
for d in thisismylist:
print d['Name']
If you want a list of those values:
>>> [d['Name'] for d in thisismylist]
['Albert', 'Suzy', 'Johnny']
Same method, you can get a tuple of the data:
>>> [(d['Name'],d['Age']) for d in thisismylist]
[('Albert', 16), ('Suzy', 17), ('Johnny', 13)]
Or, turn the list of dicts into a single key,value pair dictionary:
>>> {d['Name']:d['Age'] for d in thisismylist}
{'Johnny': 13, 'Albert': 16, 'Suzy': 17}
So, same method, a way to print them:
>>> print '\n'.join(d['Name'] for d in thisismylist)
Albert
Suzy
Johnny
And you can print it sorted if you wish:
>>> print '\n'.join(sorted(d['Name'] for d in thisismylist))
Albert
Johnny
Suzy
Or, sort by their ages while flattening the list:
>>> for name, age in sorted([(d['Name'],d['Age']) for d in thisismylist],key=lambda t:t[1]):
... print '{}: {}'.format(name,age)
...
Johnny: 13
Albert: 16
Suzy: 17
Looks like you need to go over the Python flow-control documentation. Basically, you just loop over all the items in your list, and then for each of those items (dictionaries, in this case) you can access whatever values you want. The code below, for instance, will print out every value in every dictionary inside the list.
for d in my_list:
for key in d:
print d[key]
Note that this doesn't print the keys, just the values. To print the keys as well, make your print statement print key, d[key]
. That easy!
But really, go read the flow-control documentation; it's very nice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With