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!
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.
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.
I recommend Python's list comprehensions:
print [li["id"] for li in list]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With