Python 打印列表中给定字典键的所有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18795253/
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
Print all values of a given key of dictionaries in a list
提问by user2146933
I have a list of dictionaries that looks something like this:
我有一个字典列表,看起来像这样:
list =[{"id": 1, "status": "new", "date_created": "09/13/2013"}, {"id": 2, "status": "pending", "date_created": "09/11/2013"}, {"id": 3, "status": "closed", "date_created": "09/10/2013"}]
What i want to do is be able to print all of the values in this list of dictionaries that relate to "id" If it was just 1 dictionary i know i could do like:
我想要做的是能够打印此字典列表中与“id”相关的所有值如果它只是 1 个字典,我知道我可以这样做:
print list["id"]
If it was just one dictionary, but how do i do this for a list of dictionaries? I tried:
如果它只是一本字典,但我如何为字典列表执行此操作?我试过:
for i in list:
print i['id']
but i get an error that says
但我收到一个错误提示
TypeError: string indices must be integers, not str
Can someone give me a hand? Thanks!
有人可以帮我一把吗?谢谢!
采纳答案by chepner
Somewhere in your code, your variable was reassigned a string value, instead of being a list of dictionaries.
在您的代码中,您的变量被重新分配了一个字符串值,而不是一个字典列表。
>>> "foo"['id']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not str
Otherwise, your code would work.
否则,您的代码将起作用。
>>> list=[{'id': 3}, {'id': 5}]
>>> for i in list:
... print i['id']
...
3
5
but the advice about not using list
as a name still stands.
但关于不用list
作名称的建议仍然有效。
回答by Joseph Victor Zammit
I tried the below in Python shell and it works:
我在 Python shell 中尝试了以下操作,并且可以正常工作:
In [1]: mylist =[{"id": 1, "status": "new", "date_created": "09/13/2013"}, {"id": 2, "status": "pending", "date_created": "09/11/2013"}, {"id": 3, "status": "closed", "date_created": "09/10/2013"}]
In [2]: for item in mylist:
...: print item
...:
{'status': 'new', 'date_created': '09/13/2013', 'id': 1}
{'status': 'pending', 'date_created': '09/11/2013', 'id': 2}
{'status': 'closed', 'date_created': '09/10/2013', 'id': 3}
In [3]: for item in mylist:
print item['id']
...:
1
2
3
Never use reserved words or names that refer to built-in types (as in the case of list
) as a name for your variables.
切勿使用引用内置类型的保留字或名称(如 的情况list
)作为变量的名称。
回答by JStrahl
I recommend Python's list comprehensions:
我推荐 Python 的列表推导式:
print [li["id"] for li in list]