Combine 2 dictionaries
Question:
Combine D1 (A->B) and D2 (A->C) into a new dictionary B->C
def combine(D1, D2):
"""Combines dictionaries D1 (A->B) and D2 (A->C) into a new dictionary B->C"""
# Create an empty dictionary D3:
D3={}
# Go through all keys in D1:
for key in D1:
# If the key also is in D2:
if key in D2:
# Get value_D1 for the key in D1:
value_D1 = ...
# Get value_D2 for the key in D2:
value_D2 = ...
# Add the pair value_D1:value_D2 to D3:
D3[value_D1] = ...
# Return D3:
return D3
This is fill in the blanks types help. There are 2 dicts d1 and d2 form d3.
Answers:
def combine(D1, D2):
"""Combines dictionaries D1 (A->B) and D2 (A->C) into a new dictionary B->C"""
# Create an empty dictionary D3:
D3={}
# Go through all keys in D1:
for key in D1:
# If the key also is in D2:
if key in D2:
# Get value_D1 for the key in D1:
value_D1 = D1[key]
# Get value_D2 for the key in D2:
value_D2 = D2[key]
# Add the pair value_D1:value_D2 to D3:
D3[value_D1] = value_D2
# Return D3:
return D3
#Example
d1 = {'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.'}
d2 = {'India': 'Indian',
'Canada': 'Canadian',
'United States': 'American'}
print(combine(d1,d2))
Combine D1 (A->B) and D2 (A->C) into a new dictionary B->C
def combine(D1, D2):
"""Combines dictionaries D1 (A->B) and D2 (A->C) into a new dictionary B->C"""
# Create an empty dictionary D3:
D3={}
# Go through all keys in D1:
for key in D1:
# If the key also is in D2:
if key in D2:
# Get value_D1 for the key in D1:
value_D1 = ...
# Get value_D2 for the key in D2:
value_D2 = ...
# Add the pair value_D1:value_D2 to D3:
D3[value_D1] = ...
# Return D3:
return D3
This is fill in the blanks types help. There are 2 dicts d1 and d2 form d3.
def combine(D1, D2):
"""Combines dictionaries D1 (A->B) and D2 (A->C) into a new dictionary B->C"""
# Create an empty dictionary D3:
D3={}
# Go through all keys in D1:
for key in D1:
# If the key also is in D2:
if key in D2:
# Get value_D1 for the key in D1:
value_D1 = D1[key]
# Get value_D2 for the key in D2:
value_D2 = D2[key]
# Add the pair value_D1:value_D2 to D3:
D3[value_D1] = value_D2
# Return D3:
return D3
#Example
d1 = {'India': 'Delhi',
'Canada': 'Ottawa',
'United States': 'Washington D. C.'}
d2 = {'India': 'Indian',
'Canada': 'Canadian',
'United States': 'American'}
print(combine(d1,d2))