Python Accessing Values in A List of Dictionaries

試著忘記壹切 提交于 2020-11-25 07:35:50

问题


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


回答1:


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

for d in thisismylist:
    print d['Name']



回答2:


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



回答3:


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.




回答4:


The following code should work perfectly.

for var in thisismylist:
  print var['Name']



回答5:


You could project the Name attribute out of each element in the list and join the results with newlines:

>>> print '\n'.join(x['Name'] for x in thisismylist)
Albert
Suzy
Johnny

Edit

It took me a few minutes, but I remembered the other interesting way to do this. You can use a combination of itertools and the operator module to do this as well. You can see it on repl.it too.

>>> from itertools import imap
>>> from operator import itemgetter
>>> print '\n'.join(imap(itemgetter('Name'), thisismylist))
Albert
Suzy
Johnny

In any case, you are probably better off using a vanilla for loop, but I figured that some other options were in order.




回答6:


A shorthand way to do this without importing libraries:

print('\n'.join([e["Name"] for e in thisismylist]))


来源:https://stackoverflow.com/questions/17117912/python-accessing-values-in-a-list-of-dictionaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!