use*_*123 0 python dictionary python-3.x
如何在python中访问嵌套字典.我想访问card和card1的' type '.
data = {
'1': {
'type': 'card',
'card[number]': 12345,
},
'2': {
'type': 'wechat',
'name': 'paras'
}}
Run Code Online (Sandbox Code Playgroud)
我只想从字典中输入.我怎样才能得到.我使用以下代码但收到错误:
>>> 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
Run Code Online (Sandbox Code Playgroud)
您可以使用:
In [120]: for item in data.values():
...: print(item['type'])
card
wechat
Run Code Online (Sandbox Code Playgroud)
或列表理解:
In [122]: [item['type'] for item in data.values()]
Out[122]: ['card', 'wechat']
Run Code Online (Sandbox Code Playgroud)