首页 > 解决方案 > 检查列表中是否有重复的对并替换其中一个值

问题描述

我有字典的值作为列表:

    myDict =  {'id1': ["name1","Type1","Value_1"],
    'id2': ["name2","Type1","Value_2"],
    'id3': ["name1","Type2","Value_3"],
    'id4': ["name1","Type1","Value_4"]
    }

我想遍历字典并查看名称和类型对是否已经在列表中 - 用任何其他替换“类型 1”值,结果字典将是:

    myDict =  {'id1': ["name1","Type1","Value_1"],
    'id2': ["name2","Type1","Value_2"],
    'id3': ["name1","Type2","Value_3"],
    'id4': ["name1","Modified_Type 1","Value_4"]
    }

目前不知道如何用 Python 处理它

主要是关于比较 value[0]、value[1] 以及两者在其他列表中是否相同的问题 - 替换它。

我正在尝试遍历现有字典并比较它的值是否不在 newDictionary 中,但显然我正在检查这些值是否单独存在于 newDict 值中,而不是作为对:

    myDict =  {'id1': ["name1","Type1","Value_1"],
    'id2': ["name2","Type1","Value_2"],
    'id3': ["name1","Type2","Value_3"],
    'id4': ["name1","Type1","Value_4"]
    }
    newDict = {}
    for key, value in myDict.items():
        if value[0] not in newDict.values() and value[1] not in newDict.values():
    newDict[key] = value
    else:
        newDict[key] = [value[0],"Some modified value",value[2]]
  print (newDict)

标签: python

解决方案


目前还不清楚您到底想要什么,因为您的结果包含 Type1 两次......但这是一种开始正确道路的方法。

听起来您希望对您的 id 进行排序。所以你可以得到一个排序的键列表,如下所示:

keys = sorted(myDict) #thanks @abarnert

然后遍历并检查类型:

existingTypes = []
for key in keys:
    theType = myDict[key][1]
    if theType in existingTypes:
        myDict[key][1] = "Modified_" + theType
    else:
        existingTypes.push(theType)

编辑 - 更新您更新的问题:

这可能不是最干净的,但它会起作用:

myDict =  {'id1': ["name1","Type1","Value_1"],
'id2': ["name2","Type1","Value_2"],
'id3': ["name1","Type2","Value_3"],
'id4': ["name1","Type1","Value_4"]
}

newDict = {}
for key in sorted(myDict):
    value = myDict[key]
    valuesExist = False

    for newValue in newDict.values():
        if value[0] == newValue[0]  and value[1] == newValue[1]:
            valuesExist = True

    if not valuesExist:
        newDict[key] = value
    else:
        newDict[key] = [value[0],"Some modified value",value[2]]

print (newDict)

推荐阅读