user1741339
user1741339

Reputation: 515

dictionary merging for certain keys

So I want to try and merge only certain keys from one dictionary to another so doing

a = {'a':2, 'b':3, 'c':5}
b = {'d':2, 'e':4}
a.update(b)
>>> a
{'a': 2, 'c': 5, 'b': 3, 'e': 4, 'd': 2} # returns a merge of all keys

However say you only wanted the key and value pair 'd':2 and not all of the elements within the dictionary how would this be possible so you get:

{'a': 2, 'c': 5, 'b': 3, 'd': 2}

Upvotes: 0

Views: 50

Answers (3)

Marek Lewandowski
Marek Lewandowski

Reputation: 3401

You may use following snippet:

a = {'a':2, 'b':3, 'c':5}
b = {'d':2, 'e':4}

desiredKeys = ('d',)

for key, val in b.items():
    if key in desiredKeys:
        a[key] = b[key]

print( a )

Sample above will output:

{'d': 2, 'b': 3, 'c': 5, 'a': 2}

Upvotes: 0

whatyouhide
whatyouhide

Reputation: 16781

I don't know if I got what you're asking. Anyway, if you want to update just some keys on a dictionary with keys from another, you can do:

a['d'] = b['d']

or, if you want to update multiple keys:

for to_update in keys_to_update: # keys_to_update is a list
    a[to_update] = b[to_update]

Upvotes: 0

eumiro
eumiro

Reputation: 212835

If you know you want to update a with b['d'], use this:

a['d'] = b['d']

Upvotes: 2

Related Questions