请帮我查看嵌套词典:
moo = {'dell': {'strength': {}, 'weakness': {}},'ibm': {'strength': {}, 'weakness': {}}}
我可以使用以下方式访问父键:
for k in moo.keys():
print k
如何访问子键?
答案 0 :(得分:2)
只需遍历每个项目:
for k in moo.keys():
print k # 1st level key
for sk in moo[k].keys():
print sk # 2nd level subkey
这应该打印
ibm
weakness
strength
dell
weakness
strength
答案 1 :(得分:1)
使用dict.items()
方法!
for maker, properties in moo.items():
for property, values in properties.items():
print(maker, property, values)
输出:
dell strength {}
dell weakness {}
ibm strength {}
ibm weakness {}
要访问单个元素,只需链接[key]
- 调用:
moo['dell']['strength']
输出:
{}
答案 2 :(得分:0)
使用嵌套for循环:
for k in moo:
for i in k.keys():
print i
或直接访问它们:
moo['dell']['strength']