的一部分的字典,我經常用這個結構發現自己:用dict2
一個子集更新dict1
的更新與另一個字典
dict1['key1'] = dict2['key1']
dict1['key2'] = dict2['key2']
dict1['key3'] = dict2['key3']
類。
我覺得沒有在形式
什麼方法,你通常需要做同樣的事情內置的方法?你有沒有爲此做出自己的功能?它看起來像什麼?
評論?
我已經提交了idea Python的思路:
有時候你想要的字典這是另一個字典的子集。這將很好,如果 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))))
[email protected]:~/Desktop$ python test.py
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
{1: 'one', 3: 'three', 5: 'five'}
所以更新與另一個字典的一部分的字典,你可以使用:
dict1.update(dict2.items(['key1', 'key2', 'key3']))
我學到了什麼新東西 - 真的沒有任何捷徑......我喜歡這個答案 - 它更加明確。我認爲它比aquavitae的答案快,因爲它不會創建任何中間列表或生成器。 – warvariuc 2012-03-09 12:56:50