Python 3
Implement the function invert_and_merge, which takes any number of input dictionaries via a star parameter, and inverts and merges them into a single result dictionary. When inverting a dictionary, the keys and values are flipped, so that each value maps to a set containing the corresponding key(s) in the original dictionary. When merging the inverted dictionaries, sets corresponding to the same key are combined.
Examples:
def invert_and_merge(*dicts):
rdict = {}
# YOUR CODE HERE
return rdict
Code
def invert_and_merge(*dicts):
rdict = {}
#iterate the dicts
for i in dicts:
for item,value in i.items():
#cehck if value is in rdict
#if yes then add the value to the place
if value in rdict:
rdict[value].add(item)
#else create new entry in rdict
else:
rdict[value]={item}
return rdict
print(invert_and_merge({'a': 1, 'b': 2, 'c': 1, 'd': 1, 'e': 2}))
print(invert_and_merge({'a': 'apple', 'b': 'bee', 'c': 'cat'},
{'insect': 'bee', 'mammal': 'cat', 'feline': 'cat'},
{'citrus': 'orange', 'pome': 'apple', 'pollinator': 'bee'}))
Screenshot
Output
Get Answers For Free
Most questions answered within 1 hours.