如何更新字典及其列表内容?

时间:2018-07-15 20:43:59

标签: 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]}

如何更新和过滤字典列表中的重复项?

5 个答案:

答案 0 :(得分:2)

public void checkRingtones() { boolean bModified = false; DatabaseHelper ringtonesDB = new DatabaseHelper(this); while(ringtoneCursor.moveToNext()) { File ringtoneFile = new File(ringtonesCursor.getString(2)); if(!ringtoneFile.exists()) { bModified = true; ringtonesDB.delete(ringtonesCursor.getInt(0)); Log.e("SL", "Ringtone \"" + ringtonesCursor.getString(2) + "\" cannot be found and therefore will be deleted!"); } } if(bModified) getRingtones(); } 替换现有键下的值,这解释了您得到的结果(您的值是整数列表,但是public void checkRingtones() { if(ringtonesCursor.getCount() < 1) { return; } boolean bModified = false; DatabaseHelper ringtonesDB = new DatabaseHelper(this); if(ringtonesCursor.moveToFirst()) Log.v("SL", "Moved successfully to first row."); do { File ringtoneFile = new File(ringtonesCursor.getString(2)); if(!ringtoneFile.exists()) { bModified = true; ringtonesDB.delete(ringtonesCursor.getInt(0)); Log.e("SL", "Ringtone \"" + ringtonesCursor.getString(2) + "\" cannot be found and therefore will be deleted!"); } } while (ringtonesCursor.moveToNext()); if(bModified) getRingtones(); } 方法不知道,而且无论如何都不知道如何合并数据)

在这里,您已经创建了一个专门的字典,其值是整数列表。

您想要的是自定义合并函数。

我将使用对键的并集的dict理解来重建第三个dict,然后将列表合并为一组(用于统一性),然后返回列表:

dict.update

结果:

update

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来保证对整数值进行排序。

答案 1 :(得分:1)

您可以创建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]}

答案 2 :(得分:0)

由于您的词典包含列表,因此我们可以执行以下操作-

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

显然,此方法是 hacky ,但可以解决问题。您可能应该会看到Jean's的答案,因为此答案是可以完成 的方式,但总是有更好的方法

答案 3 :(得分:0)

可能不是最有效的方法,但是一种方法可能如下:

  • 迭代其中一个字典的键,并检查其他字典中是否存在相同的键。
  • 如果存在,则更新不存在的值(您可以为此目的使用set或循环值)。
  • 如果它不存在,则添加键并将值复制到字典中。

dict1 = {'temp1':[1,2,3,4]}
dict2 = {'temp1': [3,4,5],'temp2':[15,16,17]}


for key in dict2: # check over keys in dict2
    if key in dict1: # if key also exist in dict1 then update values
        for v in dict2[key]:
            if v not in dict1[key]:  # update values only if does not exist
                dict1[key].append(v)
    else: # if key does not exist copy the values from dict2 for the key
        dict1[key] = dict2[key][:]

# dict1 is {'temp2': [15, 16, 17], 'temp1': [1, 2, 3, 4, 5]}

答案 4 :(得分:0)

如果他们不能重复,为什么不从头开始使用集呢?

mapply

返回:

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)
相关问题