我有一个多维字典,我无法添加新元素。你能帮忙解决这个问题:
items = {'Warner': {'balls': 4, 'runs': 6},
'Dhawan': {'balls': 2, 'runs': 0},
'yuvaraj': {'balls': 1.5, 'runs': 32},
'scouts': {'balls': 3, 'runs': 15}
}
对此,我想添加一个新元素
items['varun'] = [{'balls': 2}, {'runs': 2}]
但是,上面的行引发了一个错误,说明密钥错误Varun。
在你的第一篇文章中
`items = {'Warner': {'balls': 4, 'runs': 6 },
'Dhawan': {'balls': 2, 'runs': 0 },
'yuvaraj': {'balls': 1.5, 'runs': 32},
'scouts': {'balls': 3, 'runs': 15},
}`
你有一个与dict
匹配的key
,但是你试图匹配list
的dict
,而不仅仅是dict
。试试这个:
items['varun'] = {'balls':2 , 'runs' : 2}
输出:
{'Warner': {'balls': 4, 'runs': 6},
'Dhawan': {'balls': 2, 'runs': 0},
'yuvaraj': {'balls': 1.5, 'runs': 32},
'scouts': {'balls': 3, 'runs': 15},
'varun': {'balls': 2, 'runs': 2}}