Question

Python 3 Implement the function invert_and_merge, which takes any number of input dictionaries via a star...

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:

  • invert_and_merge({'a': 1, 'b': 2, 'c': 1, 'd': 1, 'e': 2})
    should return {1: {'a', 'c', 'd'}, 2: {'b', 'e'}}
  • invert_and_merge({'a': 'apple', 'b': 'bee', 'c': 'cat'},
    {'insect': 'bee', 'mammal': 'cat', 'feline': 'cat'},
    {'citrus': 'orange', 'pome': 'apple', 'pollinator': 'bee'})
    should return {'apple': {'a', 'pome'},
    'bee': {'b', 'insect', 'pollinator'},
    'cat': {'c', 'feline', 'mammal'},
    'orange': {'citrus'}}

def invert_and_merge(*dicts):
rdict = {}
# YOUR CODE HERE
return rdict

Homework Answers

Answer #1

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

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT