Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Accessing Values in A List of Dictionaries

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...

like image 597
user2487686 Avatar asked Jun 14 '13 22:06

user2487686


People also ask

How can I get a list of values from a dictionary?

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.

Can dictionary values be a list Python?

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!


3 Answers

If you're just looking for values associated with 'Name', your code should look like:

for d in thisismylist:
    print d['Name']
like image 140
user2479509 Avatar answered Sep 24 '22 03:09

user2479509


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
like image 29
dawg Avatar answered Sep 26 '22 03:09

dawg


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.

like image 23
Henry Keiter Avatar answered Sep 22 '22 03:09

Henry Keiter