Python 如何更新字典及其列表内容?
我已经创建了两个字典,我希望这样组合:Python 如何更新字典及其列表内容?,python,list,dictionary,Python,List,Dictionary,我已经创建了两个字典,我希望这样组合: dict1 = {'temp1':[1,2,3,4]} dict2 = {'temp1': [3,4,5],'temp2':[15,16,17]} dict1.update(dict2) 我希望得到这个: dict1 = {'temp1': [1, 2, 3, 4, 5], 'temp2': [15, 16, 17]} dict1 = {'temp1': [3, 4, 5], 'temp2': [15, 16, 17]} 但我得到的却是: dict1
dict1 = {'temp1':[1,2,3,4]}
dict2 = {'temp1': [3,4,5],'temp2':[15,16,17]}
dict1.update(dict2)
我希望得到这个:
dict1 = {'temp1': [1, 2, 3, 4, 5], 'temp2': [15, 16, 17]}
dict1 = {'temp1': [3, 4, 5], 'temp2': [15, 16, 17]}
但我得到的却是:
dict1 = {'temp1': [1, 2, 3, 4, 5], 'temp2': [15, 16, 17]}
dict1 = {'temp1': [3, 4, 5], 'temp2': [15, 16, 17]}
如何更新和过滤字典列表中的重复项?dict.update
替换现有键下的值,这解释了您得到的结果(您的值是整数列表,但update
方法不知道这一点,也不知道如何合并数据)
在这里,您创建了一个专门的字典,其中的值是整数列表
您需要的是一个自定义合并函数
我将在键的并集上使用dict理解重建第三个dict,并将列表合并为一个集合(用于唯一性),然后返回列表:
dict1 = {'temp1':[1,2,3]}
dict2 = {'temp1': [3,4,5],'temp2':[15,16,17]}
dict3 = {k:list(set(dict1.get(k,[])+dict2.get(k,[]))) for k in set(dict2) | set(dict1)}
print(dict3)
结果:
{'temp2': [16, 17, 15], 'temp1': [1, 2, 3, 4, 5]}
dict1.get(k,[])
的神奇之处在于,如果键不存在,它将返回一个空列表,这样+
就可以工作,表达式也不会太复杂
由于在某些时候使用了
集合
,因此无法保证元素的顺序。您可以使用排序(set…
,而不是简单地转换到列表
,以确保整数值已排序。由于您的dict包含列表,我们可以这样做-
dict1 = {'temp1':[1,2,3]}
dict2 = {'temp1': [3,4,5],'temp2':[15,16,17]}
for k, v in dict1.iteritems():
try:
dict2[k] = list(set(dict2[k]+v))
except KeyError:
pass
很明显,这种方法很粗糙,但解决了这个问题。您可能会看到答案,因为这个答案是如何做某事的,但总是有更好的方法来做它的,您可以创建一个子类
dict
,它更新列出您想要的方式:
from collections import UserDict
class ListDict(UserDict):
def __init__(self, data_as_dict):
self.data = data_as_dict
def update(self, other):
for key, sublist in other.items():
self.data[key] = list(set(self.data.get(key, [])) | set(sublist))
dict1 = {'temp1':[1,2,3]}
dict2 = {'temp1': [3,4,5],'temp2':[15,16,17]}
d = ListDict(dict1)
d.update(dict2)
print(d)
# {'temp1': [1, 2, 3, 4, 5], 'temp2': [16, 17, 15]}
可能不是最有效的方法,但有一种方法可能如下所示:
- 迭代其中一个字典的键,并检查其他字典中是否存在相同的键
- 如果存在,则更新不存在的值(可以使用set或循环值)
- 如果不存在,则向字典添加键并复制值
如果他们不能重复,为什么不从一开始就使用集合呢
dict1 = {'temp1': {1,2,3,4}}
dict2 = {'temp1': {3,4,5},'temp2':{15,16,17}}
for k,v in dict2.items():
dict1[k] = v.union(dict1.get(k,{}))
print(dict1)
返回:
{'temp1': {1, 2, 3, 4, 5}, 'temp2': {15, 16, 17}}
我不知道有什么方法可以做到这一点,你必须循环每一个,并设置一个if条件。如果在dict中,则更新其他方式更新(追加)…您是否关心内部值的顺序?如果只使用集合而不是列表就好了。这不会过滤掉重复项。这就是Python2,因为iteritems()。此外,这种方法是不对称的:如果dict1中的键比dict2中的键多,那么它就不起作用。哦,对不起,没有看到重复的部分,让我编辑它