Python 中如何对单个字典中同一个 key 的值进行合并?
迷茫
迷茫 2017-04-18 10:23:07
0
2
774

搜索未果,希望能够得到帮助:

现在有一个字典

dict = {'A1':12 24 42} 

现在我需要得到这个字典中同一个 key 的值,即返回 12+24+42的结果,要如何合并呢?(value 有多个,不一定为 3 个)

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
左手右手慢动作

A key in a dictionary cannot have multiple values ​​in Python
The above writing is incorrect
If you want a key to have multiple values, you must use a list to store the values

dic = {'A1':[12,24,42]}

It is very convenient to calculate the sum in this way, as long as

for key in dic:
    dic[key] = sum(dic[key])
print(dic) # {'A1': 78}
PHPzhong

The situation mentioned by the poster that the dictionary is in key-value format does not exist at all. A dictionary cannot have duplicate KEYs, and of course each key has only one value

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!