How to add multiple values to a key in a Python dictionary -
i trying create dictionary values in name_num
dictionary length of list new key , name_num
dictionary key , value value. so:
name_num = {"bill": [1,2,3,4], "bob":[3,4,2], "mary": [5, 1], "jim":[6,17,4], "kim": [21,54,35]}
i want create following dictionary:
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, code gets me closest:
for mykey in name_num: new_dict[len(name_num[mykey])] = {mykey: name_num[mykey]}
output:
new_dict = {4:{"bill": [1,2,3,4]}, 3:{"jim":[6,17,4]}, 2:{"mary": [5, 1]}}
i know need loop through code somehow can add other values key 3.
dictionary, associative array or map (many names, same functionality) property keys unique.
the keys wish have, integers, not unique if lengths same, that's why code doesn't work. putting new value existing key means replacing old value.
you have add key-value pairs existing value dictionaries.
for mykey in name_num: length = len(name_num[mykey]) if length in new_dict: # key present in new dictionary new_dict[length][mykey] = name_num[mykey] else: new_dict[length] = {mykey: name_num[mykey]}
should trick
Comments
Post a Comment