Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print all values of a given key of dictionaries in a list

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!

like image 707
user2146933 Avatar asked Sep 13 '13 21:09

user2146933


3 Answers

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.

like image 130
chepner Avatar answered Nov 15 '22 21:11

chepner


I tried the below in 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 that refer to built-in types (as in the case of list) as a name for your variables.

like image 29
Joseph Victor Zammit Avatar answered Nov 15 '22 20:11

Joseph Victor Zammit


I recommend Python's list comprehensions:

print [li["id"] for li in list]
like image 37
JStrahl Avatar answered Nov 15 '22 20:11

JStrahl