test123
test123

Reputation: 127

Merge two dictionaries while sharing the keys

I'm trying to build a small program that, given a dictionary containing names and addresses and another dictionary that contains names and phone numbers, the output should merge them both (and not overwrite one another). The final output dictionary should contain name, address (if available) and phone (if available). Here's an example:

addr = {'George': 'via Wagner, 23', 'White': 'Piazza Bologna, 1',
    'L. Red': 'via A. Einstein, 12', 'Pete': 'via Pio'}
phone = {'Mark': '347 8987989', 'George': '06 89786765',
     'Mauro B.': '3489878675', 'Pete': '07897878', 'L. Red': '09877887'}

And the final dictionary:

addr_phone(addr, phone) -->
{'George':    {'address': 'via Wagner, 23'},
 'Mark':      {'phone': '347 8987989'},
 'George':    {'phone': '06 89786765'},
 'L. Red':   {'phone': '09877887', 'address': 'via A. Einstein, 12'},
 'Pete':       {'phone': '07897878', 'address': 'via Pio'},
 'Mauro B.':   {'phone': '3489878675'},
 'White': {'address': 'Piazza Bologna, 1'}}

I tried writing this:

def addr_phone(addr, phone):
    d3={}
    d3.update(addr)
    d3.update(phone)
    for k,v in phone.items():
        if k not in addr:
            d3[k]=v
    return d3

But I get multiple instances of the same name, and it's not what I want. Thanks for your help.

Upvotes: 2

Views: 175

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121952

Use a defaultdict:

from collections import defaultdict

out = defaultdict(dict)
for name, phonenumber in phone.iteritems():
    out[name]['phone'] = phonenumber
for name, address in addr.iteritems():
    out[name]['address'] = address

For python 3 just replace .iteritems() with .items():

out = defaultdict(dict)
for name, phonenumber in phone.items():
    out[name]['phone'] = phonenumber
for name, address in addr.items():
    out[name]['address'] = address

You do need to loop over both input dictionaries, because you are moving the values to a new dictionary per name.

Upvotes: 4

Related Questions