我经常发现自己在使用这个构造:
dict1['key1'] = dict2['key1']
dict1['key2'] = dict2['key2']
dict1['key3'] = dict2['key3']
一种用CCD_ 2的子集更新CCD_。
我认为没有一种构建的方法可以在形式中做同样的事情
dict1.update_partial(dict2, ('key1', 'key2', 'key3'))
你通常采取什么方法?你为此制作了自己的函数吗?它看起来怎么样?
评论?
我已经向python提交了一个想法:
有时你想要一个dict,它是另一个dict的子集。如果dict.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'}
因此,要用另一个dict的一部分更新dict,您可以使用:
dict1.update(dict2.items(['key1', 'key2', 'key3']))
你可以这样做:
keys = ['key1', 'key2', 'key3']
dict1.update((k, dict2[k]) for k in keys)
据我所知,没有内置函数,但这将是一个简单的2行:
for key in ('key1', 'key2', 'key3'):
dict1[key] = dict2[key] # assign dictionary items
如果我们假设dict1的所有密钥也在dict2中,那么最明确的方法可能是过滤dict2并使用过滤后的dict1:更新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()])