简体   繁体   中英

How to access nested dictionary in python

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

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']

When you iterate a dictionary, eg 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)

嵌套字典

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()]

You can use a NestedDict from the ndicts package.

>>> from ndicts import NestedDict
>>> data = {'1': {'type': 'card', 'card[number]': 12345},
            '2': {'type': 'wechat', 'name': 'paras'}}
>>> nd = NestedDict(data)
>>> nd.extract["", "type"]
NestedDict({'1': {'type': 'card'}, '2': {'type': 'wechat'}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM