我有一个看起来像这样的字典列表:
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 strCan 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 strOtherwise, your code would work.
>>> list=[{'id': 3}, {'id': 5}] >>> for i in list: ... print i['id'] ... 3 5but the advice about not using list as a name still stands.
更多推荐
发布评论