randomnessrandomly
randomnessrandomly

Reputation: 135

Create a Python Dictonary by taking joins of two dictionary

I have a Python dictionary, like so:

{0: 'Initialised', 1: 'Processed', 3:'Finished'}

I have a second Dictionary, like so:

{0: 81, 1: 100, 3: 906}

What I want is to get:

{'Initialised':81, 'Processed':100, 'Finished': 906}

What is the most efficient way to do this?

Upvotes: 0

Views: 76

Answers (3)

shaktimaan
shaktimaan

Reputation: 1857

Do something like this

In [31]: t1 = {0: 'Initialised', 1: 'Processed', 3:'Finished'}
In [33]: t2 = {0: 81, 1: 100, 3: 906}

In [34]: {t1[key]: t2[key] for key in t1}
Out[34]: {'Finished': 906, 'Initialised': 81, 'Processed': 100}

Without Dictionary Comprehension:

t3 = {}
for key in t1:
    t3[t1[key]] = t2[key]

Upvotes: 4

Anand S Kumar
Anand S Kumar

Reputation: 90979

Isn't it very simple ?

Example using dictionary comprehension (which is available from Python 2.7 onwards) -

>>> d1 = {0: 'Initialised', 1: 'Processed', 3:'Finished'}
>>> d2 = {0: 81, 1: 100, 3: 906}
>>>
>>> d = {d1[k]:d2[k] for k in d1.keys()}
>>> d
{'Finished': 906, 'Processed': 100, 'Initialised': 81}

Upvotes: 2

oopcode
oopcode

Reputation: 1962

Handles absence of keys in the second dict.

{v: d2.get(k, None) for k, v in d1.items()}
# {'Finished': 906, 'Initialised': 81, 'Processed': 100}

Upvotes: 3

Related Questions