在列表中打印给定键字典的所有值 [英] Print all values of a given key of dictionaries in a list

查看:120
本文介绍了在列表中打印给定键字典的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的字典列表:

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"}]

我想做的是能够列出与id相关的字典列表中的所有值如果只是一个字典,我知道我可以这样做:

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:

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!

推荐答案

在您的代码中,您的变量重新分配了一个字符串值,而不是一个字典的列表。 p>

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.

这篇关于在列表中打印给定键字典的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆