简体   繁体   中英

Update a dict with part of another dict

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']))

You could do it like this:

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

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

If we assume that all keys of dict1 which are also in dict2 should be updated then probaly the most explicit way is to filter dict2 and update dict1 using the filtered dict1:

dict1.update(
    {k: v for k, v in dict2.items() if k in dict1})
dict1.update([(key, dict2[key]) for key in dict2.keys()])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM