Skip to content Skip to sidebar Skip to footer

Adding New Values In A Typical Key In A Dictionary

how do I add value to another dictionary to the same key like below con = {'a':{'b':'c'}, b:{'d':'e'}} into con = {'a':{'b':'c', 'e':'f'}, b:{'d':'e'}}

Solution 1:

With the current set up, its always a key and a value pair, so it will be key:value

If you would like to have more than one value to a key, please use.

from collections importdefaultdictmyDict= defaultdict(list)

Now, you can add more than one value to the key.

myDict[key1].append(keyA:Value)
myDict[key1].append(keyB:Value)

Hope this helps.

Cheers!

Solution 2:

With the problem as stated, there is no reason you cannot use direct key-value assignment:

con = {'a':{'b':'c'}, 'b':{'d':'e'}} 

con['a']['e'] = 'f'print(con)

{'a': {'b': 'c', 'e': 'f'}, 'b': {'d': 'e'}}

Notice we can chain dictionary keys. This is natural because con['a'] returns a dictionary, which can itself be assigned a new key-value pair.

Post a Comment for "Adding New Values In A Typical Key In A Dictionary"