如何在多维数组中添加额外的元素?

问题描述 投票:-1回答:1

我有一个多维字典,我无法添加新元素。你能帮忙解决这个问题:

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。

python python-3.x dictionary
1个回答
1
投票

在你的第一篇文章中

 `items = {'Warner': {'balls': 4,   'runs': 6 },
         'Dhawan':  {'balls': 2,   'runs': 0 },
          'yuvaraj': {'balls': 1.5, 'runs': 32},
          'scouts':   {'balls': 3,   'runs': 15},
        }`

你有一个与dict匹配的key,但是你试图匹配listdict,而不仅仅是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}}
© www.soinside.com 2019 - 2024. All rights reserved.