Python 访问字典列表中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17117912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:30:27  来源:igfitidea点击:

Python Accessing Values in A List of Dictionaries

pythonlistdictionary

提问by user2487686

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:

我将如何使用 for 循环打印以下内容:

Albert
Suzy
Johnny

I just cant wrap my head around this idea...

我只是无法围绕这个想法...

回答by Henry Keiter

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.

看起来您需要查看Python 流控制文档。基本上,您只需遍历列表中的所有项目,然后对于这些项目中的每一个(在本例中为字典),您就可以访问您想要的任何值。例如,下面的代码将打印出列表中每个字典中的每个值。

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!

请注意,这不会打印键,只打印值。要打印密钥,请制作您的打印语句print key, d[key]。这么简单!

But really, go read the flow-control documentation; it's very nice.

但实际上,请阅读流量控制文档;这是很不错的。

回答by user2479509

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

如果您只是在寻找与“名称”相关联的值,您的代码应如下所示:

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

回答by D.Shawley

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

您可以将Name属性从列表中的每个元素中投影出来,并使用换行符连接结果:

>>> 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 itertoolsand the operatormodule to do this as well. You can see it on repl.it too.

我花了几分钟,但我想起了另一种有趣的方法来做到这一点。您也可以使用itertoolsoperator模块的组合来执行此操作。你也可以在 repl.it 上看到它

>>> 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 forloop, but I figured that some other options were in order.

无论如何,您最好使用香草for循环,但我认为还有其他一些选择。

回答by dawg

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

回答by JStrahl

A shorthand way to do this without importing libraries:

在不导入库的情况下执行此操作的速记方法:

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

回答by Phantom Coder

The following code should work perfectly.

以下代码应该可以完美运行。

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