Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a dict with part of another dict

Tags:

python

I often find myself using this construct:

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

Kind of updating dict1 with a subset of dict2.

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

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

What approach you usually take? Have you made you own function for that? How it looks like?

Comments?


I have submitted an idea to python-ideas:

Sometimes you want a dict which is subset of another dict. It would nice if dict.items accepted an optional list of keys to return. If no keys are given - use default behavior - get all items.

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 with a part of another dict, you would use:

dict1.update(dict2.items(['key1', 'key2', 'key3']))
like image 619
warvariuc Avatar asked Mar 09 '12 09:03

warvariuc


Video Answer


2 Answers

You could do it like this:

keys = ['key1', 'key2', 'key3']
dict1.update((k, dict2[k]) for k in keys)
like image 86
aquavitae Avatar answered Sep 25 '22 03:09

aquavitae


There is no built-in function I know of, but this would be a simple 2-liner:

for key in ('key1', 'key2', 'key3'):
    dict1[key] = dict2[key]  # assign dictionary items
like image 28
Constantinius Avatar answered Sep 23 '22 03:09

Constantinius