Print all values ​​of a given dictionary key in a list

I have a list of dictionaries that look 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 the ability to print all the values ​​in this list of dictionaries that are related to "id". If it were only one dictionary that I know, I could do this:

 print list["id"] 

If it was only one dictionary, but how to do it for a list of dictionaries? I tried:

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

but i get an error

 TypeError: string indices must be integers, not str 

Can someone give me a hand? Thanks!

+4
source share
2 answers

Somewhere in your code, your variable has been reassigned to 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 will work.

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

but the advice on not using list as a name is still worth it.

+6
source

I tried the following in a Python shell and it works:

 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 related to built-in types (as in the case of list ) as the name for your variables.

+3
source

Source: https://habr.com/ru/post/1502120/


All Articles