DPdl
DPdl

Reputation: 755

Replacing values of a dictionary in python

I have a dictionary that looks like this:

d1 = {('a', 'b'): 300.0,
 ('b, 'c'): '0.1*K1',
 ('a', 'c'): 0.462,
 ('c', 'e'): '0.2*K2',
 ('b', 'a'): '0.1*K1',
 ('c','d'): 'K1*K3'}
K1, K2, K3 = 2.1, 3.4, 2

I want to replace '0.1*K1' in d1 with 0.1*K1 and '0.2*K2' in d2 with 0.2*K2, and so on. The values in d1 that need to be replaced are given as keys in d2, and they are to be replaced with corresponding values in d2:

d2 = {'0.1*K1':0.1*K1, '0.1*K2':'0.1*K2', 'K2*K3':K2*K3}

The end result would be a dictionary:

d1_new = {('a', 'b'): 300.0,
     ('b, 'c'): 0.21,
     ('a', 'c'): 0.462,
     ('c', 'e'): 0.68,
     ('b', 'a'): 0.21',
     ('c','d'): 6.8}

Upvotes: 1

Views: 65

Answers (3)

U13-Forward
U13-Forward

Reputation: 71570

Use dictionary comprehension with get:

d1_new = {k: d2.get(v, v) for k, v in d.items()}

Output:

{('a', 'b'): 300.0, ('b', 'c'): 0.21000000000000002, ('a', 'c'): 0.462, ('c', 'e'): 0.68, ('b', 'a'): 0.21000000000000002, ('c', 'd'): 4.2}

Upvotes: 1

Nick
Nick

Reputation: 147146

You could use a dictionary comprehension:

d1_new = { k : d2[v] if v in d2 else v for (k, v) in d1.items() }

assuming you change d2 to this:

d2 = {'0.1*K1':0.1*K1, '0.2*K2':0.2*K2, 'K1*K3':K1*K3}

so that they keys in d2 do match what is in d1, then the output is as you desire:

{
    ('a', 'b'): 300.0,
    ('b', 'c'): 0.21000000000000002,
    ('a', 'c'): 0.462,
    ('c', 'e'): 0.68,
    ('b', 'a'): 0.21000000000000002,
    ('c', 'd'): 4.2
}

Upvotes: 1

Jordan Brière
Jordan Brière

Reputation: 1055

You could use eval to evaluate the expression:

d2 = {key: eval(str(value)) for key, value in d1.items()}

Which would result into:

{
    ('a', 'b'): 300.0,
    ('b', 'c'): 0.21000000000000002,
    ('a', 'c'): 0.462,
    ('c', 'e'): 0.68,
    ('b', 'a'): 0.21000000000000002,
    ('c', 'd'): 4.2
}

Upvotes: 1

Related Questions