-1

I'm new to Python and I'm learning about dictionaries and I'd like to clarify something.

Let's say I have two dicts: d1 = {'id1' : '1', 'id2' : '2', 'id3' : '3', 'id4' : '4'} and d2 = {'fruit1': 'Apple', 'fruit2': 'Banana', 'fruit3': 'Strawberry', 'fruit4': 'Kiwi'}. I'd like to create a new dictioanry d3 with the following content: { 1 : Apple, 2 : Banana, 3 : Strawberry, 4 : Kiwi}.

I've read this post How to merge two dictionaries in a single expression? but it's not exactly what I'm looking for.

What's the best way to create this new dictionary? Thanks!

1 Answers1

1

Use dict and zip:

  • This will work as long as both dicts are aligned
    • Modern python dict order is guaranteed to be insertion order as of v3.7, but should also be the case for v3.6.
  • The values of d1 are str type, so when they are made into keys of d3, they will be str, not int.
d1 = {'id1' : '1', 'id2' : '2', 'id3' : '3', 'id4' : '4'} 
d2 = {'fruit1': 'Apple', 'fruit2': 'Banana', 'fruit3': 'Strawberry', 'fruit4': 'Kiwi'}

d3 = dict(zip(d1.values(), d2.values()))

print(d3)

>>> {'1': 'Apple', '2': 'Banana', '3': 'Strawberry', '4': 'Kiwi'}

If you want the keys to be int type:

  • map int to the d1.values()
d3 = dict(zip(map(int, d1.values()), d2.values()))

print(d3)

>>> {1: 'Apple', 2: 'Banana', 3: 'Strawberry', 4: 'Kiwi'}
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • As mentioned in this answer, this only works if the dicts are aligned. In some versions of python, there is no guarantee on the order of keys/values. https://stackoverflow.com/questions/1867861/how-to-keep-keys-values-in-same-order-as-declared – Jason S Oct 18 '19 at 23:41