如果它们的值相似,则合并字典的键:Python

时间:2020-07-05 16:58:30

标签: python-3.x dictionary

让我们说我有以下两个字典:

10/70

我想比较他们的价值观。如果它们具有相似的值,我想组合它们的键。例如,10和70的值为0.28,我想将它们合并为20/60。因此,对于20和60,则为50/100。类似地,将50和100与30/-一样。

例如,对于其余部分,仅在dict1中仅存在0.16,因此我想将其表示为-/80。同样,对于dict2中的80,在dict1中没有匹配项,因此我想将其设置为10/70

此外,对于第一词典中的110,其值为0.28,与第一词典中的键10和第二词典中的键70相似。因此,在这种情况下,我不想重复输入两次,表示存在110/70但没有110/-。 70个重复。我希望看到updated_dict = {10:10/70, 20:20/60, 30:30/-, 40:40/-, 50:50/100, 60:20/60, 70:10/70, 80:-/80, 90:-/90, 100:50/100, 110:110/-}

通常,我希望看到以下结果。

for key, val in dict2.items():
    if (dict1.get(key, None) == val):
        print(str(key) + '/' + str(key))

这是我尝试的方式:

insert

但是无法得到我想要的东西。

有什么方法可以在python中实现吗?

1 个答案:

答案 0 :(得分:0)

初始化所有变量。

dict1 = {10: 0.28, 20: 0.12, 30: 0.16, 40: 0.15, 50: 0.08}
dict2 = {60: 0.12, 70: 0.28, 80: 0.17, 90: 0.19, 100: 0.08}
dict3 = dict()

接下来,我们必须创建一个函数来反转字典的键值对,以便我们可以获取值的键。

def reverse(dictionary):
    dict_reverse = dict()
    for key, value in dictionary.items():
        dict_reverse[value] = key
    return dict_reverse

接下来,我们检查两个字典中是否都存在该值。然后,将密钥添加到dict3。

for key, val in dict2.items():
    if val in dict1.values():
        key2 = reverse(dict1)[val]
        dict3[key2] = str(key2) + "/" + str(key)
        dict3[key] = str(key2) + "/" + str(key)
        dict1[key2] = “”
        dict2[key] = “”
    else:
        dict3[key] = "-/" + str(key)

然后我们检查dict1中是否有任何值,而dict2中没有。然后将这些值的键添加到dict3

for key, val in dict1.items():
        if val not in dict2.values():
            dict3[key] = str(key) + "/-"

结果-

dict3 = {20: '20/60', 60: '20/60', 110: '110/70', 70: '110/70', 80: '-/80', 90: '-/90', 50: '50/100', 100: '50/100', 10: '10/-', 30: '30/-', 40: '40/-'}