如何在Python字典中的键中添加多个值 [英] How to add multiple values to a key in a Python dictionary
问题描述
我正在尝试根据name_num
字典中的值创建一个字典,其中列表的长度是新键,而name_num
字典中的键和值是值.所以:
I am trying to create a dictionary from the values in the name_num
dictionary where the length of the list is the new key and the name_num
dictionary key and value are the value. So:
name_num = {"Bill": [1,2,3,4], "Bob":[3,4,2], "Mary": [5, 1], "Jim":[6,17,4], "Kim": [21,54,35]}
我要创建以下字典:
new_dict = {4:{"Bill": [1,2,3,4]}, 3:{"Bob":[3,4,2], "Jim":[6,17,4], "Kim": [21,54,35]}, 2:{"Mary": [5, 1]}}
我尝试了许多变体,但是这段代码使我最接近:
I've tried many variations, but this code gets me the closest:
for mykey in name_num:
new_dict[len(name_num[mykey])] = {mykey: name_num[mykey]}
输出:
new_dict = {4:{"Bill": [1,2,3,4]}, 3:{"Jim":[6,17,4]}, 2:{"Mary": [5, 1]}}
我知道我需要以某种方式遍历代码,以便可以将其他值添加到键3中.
I know I need to loop through the code somehow so I can add the other values to key 3.
推荐答案
词典,关联数组或地图(许多名称,基本上具有相同的功能)属性是键是唯一的.
Dictionary, associative array or map (many names, basically the same functionality) property is that keys are unique.
如果长度相同,则希望拥有的键(整数)不是唯一的,这就是为什么代码无法正常工作的原因.为现有键输入新值意味着替换旧值.
The keys you wish to have, which are integers, are not unique if lengths are the same, that's why your code doesn't work. Putting a new value for existing key means replacing the old value.
您必须将键值对添加到现有的值字典中.
You have to add key-value pairs to the existing value dictionaries.
for mykey in name_num:
length = len(name_num[mykey])
if length in new_dict: # key already present in new dictionary
new_dict[length][mykey] = name_num[mykey]
else:
new_dict[length] = {mykey: name_num[mykey]}
应该可以解决问题
这篇关于如何在Python字典中的键中添加多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!