1

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
jpp
  • 159,742
  • 34
  • 281
  • 339
user_123
  • 426
  • 7
  • 23

3 Answers3

5

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']
llllllllll
  • 16,169
  • 4
  • 31
  • 54
2

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)
jpp
  • 159,742
  • 34
  • 281
  • 339
-2

nested dict

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()]
Shaina Raza
  • 1,474
  • 17
  • 12