I just started learning python and was wondering if its possible to pair two identical keys?
example:
my_dict= {1:a,3:b,1:c}
and I want to make a new dict, something like this:
new_dict= {1:{a,c},3:{b}}
thanks for the help
I just started learning python and was wondering if its possible to pair two identical keys?
example:
my_dict= {1:a,3:b,1:c}
and I want to make a new dict, something like this:
new_dict= {1:{a,c},3:{b}}
thanks for the help
You can't have identical keys, that is the definition of dictionary. As soon as you add again the same key, the previous entry is deleted
From what I understand, you're trying to combine the two dictionaries. Given that you cannot have same keys in a dictionary, I'll suppose you have two distinct dictionaries you'd like to combine to obtain your combination.
Ex:
dic1 = {'a': 1, 'b': 2, 'c': 3}
dic2 = {'c': 4, 'd': 5, 'e': 6}
And the combination would produce:
{'a': {1}, 'b': {2}, 'c':{3, 4}, 'd': {4}, 'e': {6}}
You could use this Example:
from itertools import chain
from collections import defaultdict
dic1 = {'A': 1, 'B': 2, 'C': 3}
dic2 = {'C': 4, 'D': 5, 'E': 6}
dic = defaultdict(set)
for k, v in chain(dic1.items(), dic2.items()):
dic[k].add(v)
print(dict(dic))
Something to note:
You could instead of using set, use list in the defaultdict() argument and have a dictionary as so:
{'a': [1], 'b': [2], 'c':[3, 4], 'd': [4], 'e': [6]}
But to do so, dic[k].append(v) would be used in the for loop. You add items to sets, append to lists.
Dictionaries in Python, or any hash-able type for that matter, will not allow duplicate keys. If two duplicate keys are found in a dictionary, the key farthest in the dictionary will be persevered. This behavior can be obsevered first hand:
>>> my_dict= {1:'a',3:'b',1:'c'}
>>> my_dict
{1: 'c', 3: 'b'}
>>> my_dict= {1:'c',3:'b',1:'a'}
>>> my_dict
{1: 'a', 3: 'b'}
>>>
The Python documentation for dict()
s touches on this matter:
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).[...].
(emphasis mine)