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

编程入门 行业动态 更新时间:2024-10-25 12:19:35
在列表中打印给定字典键的所有值(Print all values of a given key of dictionaries in a list)

我有一个看起来像这样的字典列表:

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”相关的词典列表中的所有值。如果它只是一个词典,我知道我可以这样做:

print list["id"]

如果它只是一个字典,但我如何为字典列表执行此操作? 我试过了:

for i in list: print i['id']

但我得到一个错误说

TypeError: string indices must be integers, not str

有人能帮我一把吗? 谢谢!

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:

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!

最满意答案

在代码的某个地方,您的变量被重新分配了一个字符串值,而不是一个字典列表。

>>> "foo"['id'] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: string indices must be integers, not str

否则,您的代码将起作用。

>>> list=[{'id': 3}, {'id': 5}] >>> for i in list: ... print i['id'] ... 3 5

但关于不使用list作为名称的建议仍然存在。

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.

更多推荐

本文发布于:2023-08-08 00:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466745.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   列表中   Print   values   dictionaries

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!