Reputation: 169
I have 2 Dictionaries, they both contain the same keys (or they would with a little cutting, [3:]
) but different values. I would like to replace the keys in one dictionary with the values of another. For example here is a portion of my lists:
Dict 1
"AED":"United Arab Emirates Dirham",
"AFN":"Afghan Afghani",
"ALL":"Albanian Lek",
"AMD":"Armenian Dram",
"ANG":"Netherlands Antillean Guilder",
"AOA":"Angolan Kwanza",
"ARS":"Argentine Peso"
Dict2
"USDAED":3.672301,
"USDAFN":66.800003,
"USDALL":127.000221,
"USDAMD":486.160004,
"USDANG":1.769942,
"USDAOA":165.080994,
"USDARS":15.609965
I would like a list with the first entry reading "United Arab Emirates Dirham":3.672301 Any thoughts? Please let me know. Thank you!
Upvotes: 1
Views: 70
Reputation: 92854
To change/update the first dictionary use dict.update() function:
# d1 and d2 are the first and the second dicts respectively
d1.update({k[3:]:v for k,v in d2.items()})
print(d1)
The output:
{'AFN': 66.800003, 'AOA': 165.080994, 'AED': 3.672301, 'ALL': 127.000221, 'ARS': 15.609965, 'AMD': 486.160004, 'ANG': 1.769942}
Upvotes: 0
Reputation: 140186
Do that with a one-liner (dict comprehension)
dict1={"AED":"United Arab Emirates Dirham",
"AFN":"Afghan Afghani",
"ALL":"Albanian Lek",
"AMD":"Armenian Dram",
"ANG":"Netherlands Antillean Guilder",
"AOA":"Angolan Kwanza",
"ARS":"Argentine Peso"}
dict2 = {"USDAED":3.672301,
"USDAFN":66.800003,
"USDALL":127.000221,
"USDAMD":486.160004,
"USDANG":1.769942,
"USDAOA":165.080994,
"USDARS":15.609965}
dict3 = {dict1[x[3:]]:y for x,y in dict2.items()}
print(dict3)
yields:
{'Albanian Lek': 127.000221, 'Netherlands Antillean Guilder': 1.769942,
'Armenian Dram': 486.160004, 'United Arab Emirates Dirham': 3.672301,
'Afghan Afghani': 66.800003, 'Argentine Peso': 15.609965,
'Angolan Kwanza': 165.080994}
The code recreates a third dictionary with as key: values of the first one (with the small key cutoff you mentionned, and as values: values of the second one
Note: as dicts are not ordered your "first entry" wish doesn't hold, unless you print the items sorted of course.
Upvotes: 3