Coder
Coder

Reputation: 455

How to generate a dictionary from other two dictionaries?

If

d1 = {'Mercury': 10, 'Venus': 20, 'Earth': 30, 'Mars': 40}

and

d2 = {'Ten': 'M', 'Twenty': 'V', 'Thirty': 'E', 'Forty': 'F'}

then how to generate a new dictionary where the keys belong to d1 and the values belong to d2, similar to the following dictionary:

newD = {'Mercury': 'M', 'Venus': 'V', 'Earth': 'E', 'Mars': 'F'}

How to do it through comprehension, loops or any other way?

Thanks.

Upvotes: 0

Views: 72

Answers (3)

{list(d1.keys())[k]:list(d2.values())[k] for k in range(len( d1.keys()) )}

Upvotes: 0

Samwise
Samwise

Reputation: 71454

If the association is based on order, you can use zip:

>>> d1 = {'Mercury': 10, 'Venus': 20, 'Earth': 30, 'Mars': 40}
>>> d2 = {'Ten': 'M', 'Twenty': 'V', 'Thirty': 'E', 'Forty': 'F'}
>>> {k: v for k, v in zip(d1.keys(), d2.values())}
{'Mercury': 'M', 'Venus': 'V', 'Earth': 'E', 'Mars': 'F'}

If you want to associate based on 10 -> 'Ten' etc, num2words ought to work:

>>> from num2words import num2words
>>> d1 = {'Mercury': 10, 'Venus': 20, 'Earth': 30, 'Mars': 40}
>>> d2 = {'Ten': 'M', 'Twenty': 'V', 'Thirty': 'E', 'Forty': 'F'}
>>> {k: d2[num2words(v).title()] for k, v in d1.items()}
{'Mercury': 'M', 'Venus': 'V', 'Earth': 'E', 'Mars': 'F'}

Upvotes: 3

Red
Red

Reputation: 27557

Here is how you can use the zip() method to zip up the keys of d1 with the values of d2:

d1 = {'Mercury': 10, 'Venus': 20, 'Earth': 30, 'Mars': 40}
d2 = {'Ten': 'M', 'Twenty': 'V', 'Thirty': 'E', 'Forty': 'F'}

newD = dict(zip(d1,d2.values()))
print(newD)

Output:

{'Mercury': 'M', 'Venus': 'V', 'Earth': 'E', 'Mars': 'F'}

Upvotes: 0

Related Questions