我有字典,其值作为列表:
myDict = {'id1': ["name1","Type1","Value_1"],
'id2': ["name2","Type1","Value_2"],
'id3': ["name1","Type2","Value_3"],
'id4': ["name1","Type1","Value_4"]
}
我想遍历字典,看看“名称和类型”对是否已在列表中-将“ Type 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)
答案 0 :(得分:1)
目前尚不清楚您想要什么,因为您的结果两次包含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)