Reputation: 450
How to access nested dictionary in python. I want to access 'type' of both card and card1.
data = {
'1': {
'type': 'card',
'card[number]': 12345,
},
'2': {
'type': 'wechat',
'name': 'paras'
}}
I want only type from both the dictionary. how can i get. I use the following code but getting error:
>>> for item in data:
... for i in item['type']:
... print(i)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: string indices must be integers
Upvotes: 1
Views: 5389
Reputation: 1648
from a nested python dictionary like this, if I want to access lets, say article_url, so I have to program like this
[item['article_url'] for item in obj.values()]
Upvotes: -2
Reputation: 164813
When you iterate a dictionary, e.g. for item in data
, you are iterating keys. You should use a view which contains the information you require, such as dict.values
or dict.items
.
To access the key and related type by iteration:
for k, v in data.items():
print(k, v['item'])
Or, to create a list, use a list comprehension:
lst = [v['item'] for v in data.values()]
print(lst)
Upvotes: 2
Reputation: 16434
You can use:
In [120]: for item in data.values():
...: print(item['type'])
card
wechat
Or list comprehension:
In [122]: [item['type'] for item in data.values()]
Out[122]: ['card', 'wechat']
Upvotes: 5