meller92
meller92

Reputation: 455

New dictionary from comprehension with setten keys

I've got two dictionaries:

dict1 = {'id': 1001, 'text': 'some text 1', 'key1': 11, 'key2': 12}
dict2 = {'id': 1002, 'text': 'some text 2', 'key1': 1, 'key2': 2}

And I want to get something like this, keep 'id' from' dict1 and subtract 'key1' and 'key2':

dict3 = {'id': 1001, 'key1': 10, 'key2': 10 }

I've tried as following:

dict3 = {key: dict1[key] - dict2.get(key, 0) for key in ['key1', 'key2']}

but I don't know how to keep original 'id'.

Upvotes: 0

Views: 40

Answers (2)

Kaushik NP
Kaushik NP

Reputation: 6781

Since you have only two dicts with few element, its far more easier getting your required dict manually.

>>> d3 = { 'id':dict1['id'] , 'key1':dict1['key1']-dict2['key1'] ,
           'key2':dict1['key2']-dict2['key2'] }
>>> d3
=> {'id': 1001, 'key1': 10, 'key2': 10}

Upvotes: 0

Ma0
Ma0

Reputation: 15204

Your code is fine but I would use the dict-comprehension to update the dict and not create it. That way, I could apply it to a dict that is already initialized with the desired 'id' value.

dict1 = {'id': 1001, 'text': 'some text 1', 'key1': 11, 'key2': 12}
dict2 = {'id': 1002, 'text': 'some text 2', 'key1': 1, 'key2': 2}

dict3 = {'id': dict1['id']}  # initialize it first
dict3.update({key: dict1[key] - dict2.get(key, 0) for key in ['key1', 'key2']})
print(dict3)  # {'id': 1001, 'key1': 10, 'key2': 10}

Upvotes: 4

Related Questions