将 Python 字典与列表作为值进行比较
Compare Python dictionary with list as value
我正在为 Steam 编写一个解析器机器人,它将跟踪哪些物品从 Steam 用户的库存中进出。我写了一段代码,以带有嵌套列表的字典形式获取所有用户的项目和 returns,其中 KEY = USER NAME,VALUE = ITEM NAME AND ITS QUANTITY. 现在我需要比较 Data1 和 Data2(更新后的数据)。
Data1 = {
'user1': [('AWP', 1), ('DEAGLE', 2), ('AK-47', 3)],
'user2': [('MP-7', 1), ('KNIFE', 1), ('GLOVES', 1)]
}
Data2 = {
'user1': [('AWP', 1), ('DEAGLE', 2), ('AK-47', 3), ('M4A4', 1)],
'user2': [('MP-7', 1), ('KNIFE', 1), ('GLOVES', 1), ('GLOCK-18', 1)]
}
比如Data2中出现了一个新条目,我需要将它写入第三个字典,保留key。如果项目离开 Data2(这意味着这些项目不再在用户的库存中),则必须执行相同的操作。
Result = {
'user1': [('M4A4', 1)],
'user2': [('GLOCK-18', 1)]
}
使用sets
result_addition = {d:list(set(Data2[d]) - set(Data1[d])) for d in Data2.keys()}
print(result_addition)
>> {'user1': [('M4A4', 1)], 'user2': [('GLOCK-18', 1)]}
result_missing = {d:list(set(Data1[d]) - set(Data2[d])) for d in Data2.keys()}
print(result_missing )
>> {'user1': [], 'user2': []}
def dict_diff(dict_1, dict_2):
keys = set(dict_1.keys()).union(set(dict_2.keys()))
result = {}
for key in keys:
if key not in Data1:
result[key] = Data2[key]
continue
if key not in Data2:
result[key] = Data1[key]
continue
diff1 = set(Data2[key]).difference(set(Data1[key]))
diff2 = set(Data1[key]).difference(set(Data2[key]))
result[key] = list(diff1.union(diff2))
return result
dict_diff(Data1, Data2)
我正在为 Steam 编写一个解析器机器人,它将跟踪哪些物品从 Steam 用户的库存中进出。我写了一段代码,以带有嵌套列表的字典形式获取所有用户的项目和 returns,其中 KEY = USER NAME,VALUE = ITEM NAME AND ITS QUANTITY. 现在我需要比较 Data1 和 Data2(更新后的数据)。
Data1 = {
'user1': [('AWP', 1), ('DEAGLE', 2), ('AK-47', 3)],
'user2': [('MP-7', 1), ('KNIFE', 1), ('GLOVES', 1)]
}
Data2 = {
'user1': [('AWP', 1), ('DEAGLE', 2), ('AK-47', 3), ('M4A4', 1)],
'user2': [('MP-7', 1), ('KNIFE', 1), ('GLOVES', 1), ('GLOCK-18', 1)]
}
比如Data2中出现了一个新条目,我需要将它写入第三个字典,保留key。如果项目离开 Data2(这意味着这些项目不再在用户的库存中),则必须执行相同的操作。
Result = {
'user1': [('M4A4', 1)],
'user2': [('GLOCK-18', 1)]
}
使用sets
result_addition = {d:list(set(Data2[d]) - set(Data1[d])) for d in Data2.keys()}
print(result_addition)
>> {'user1': [('M4A4', 1)], 'user2': [('GLOCK-18', 1)]}
result_missing = {d:list(set(Data1[d]) - set(Data2[d])) for d in Data2.keys()}
print(result_missing )
>> {'user1': [], 'user2': []}
def dict_diff(dict_1, dict_2):
keys = set(dict_1.keys()).union(set(dict_2.keys()))
result = {}
for key in keys:
if key not in Data1:
result[key] = Data2[key]
continue
if key not in Data2:
result[key] = Data1[key]
continue
diff1 = set(Data2[key]).difference(set(Data1[key]))
diff2 = set(Data1[key]).difference(set(Data2[key]))
result[key] = list(diff1.union(diff2))
return result
dict_diff(Data1, Data2)