Update dict with part of another dict

I often use this construct:

dict1['key1'] = dict2['key1']
dict1['key2'] = dict2['key2']
dict1['key3'] = dict2['key3']

Type of update dict1with a subset dict2.

I think there is no built-in method for doing the exact same thing in the form

dict1.update_partial(dict2, ('key1', 'key2', 'key3'))

Which approach do you usually take? Have you made your function? What does it look like?

Comments?


I introduced idea for python ideas:

Sometimes you need a dict, which is a subset of another dict. It would be nice if dict.items accepted an additional list of keys to return. If there are no keys given - use the default behavior - get all the elements.

class NewDict(dict):

    def items(self, keys=()):
        """Another version of dict.items() which accepts specific keys to use."""
        for key in keys or self.keys():
            yield key, self[key]


a = NewDict({
    1: 'one',
    2: 'two',
    3: 'three',
    4: 'four',
    5: 'five'
})

print(dict(a.items()))
print(dict(a.items((1, 3, 5))))

vic@ubuntu:~/Desktop$ python test.py 
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
{1: 'one', 3: 'three', 5: 'five'}

So, to update a dict using part of another dict, you should use:

dict1.update(dict2.items(['key1', 'key2', 'key3']))
+5
source share
3 answers

, , :

for key in ('key1', 'key2', 'key3'):
    dict1 = dict2[key]
+5

:

keys = ['key1', 'key2', 'key3']
dict1.update((k, dict2[k]) for k in keys)
+7
dict1.update([(key, dict2[key]) for key in dict2.keys()])
0

All Articles