Python 3:显示字典键值对之间的差异

时间:2017-03-17 15:40:49

标签: python dictionary

我想找到两个具有多个键值的字典之间的差异。我找到的所有示例中,字典都有一个只包含一个值的键。假设您的密钥具有多个值,如以下示例所示:

pizza_1 = {"toppings": ["cheese", "pepperoni", "mushroom"],
           "crust": ["deep dish", "hand tossed", "thin"],
           "size": ["large", "medium", "small"],
           "price": ["$12.99", "$9.99", "$7.99"]}

pizza_2 = {"toppings": ["cheese", "pepperoni", "olive"],
           "crust": ["deep dish", "traditional", "thin"],
           "size": ["large", "medium", "small"],
           "brand": ["Domino's", "Pizza Hut", "Little Caesars"]}

我想只返回两个词典中的差异,包括键和值。无论是pizza_1还是pizza_2的差异,哪个字典无关紧要。我正在寻找的例子如下:

print(differences)
"toppings": ["mushroom"]
"crust": ["hand tossed"]
"price": ["$12.99", "$9.99", "$7.99"]

我不确定它将如何输出,但我想举例说明我在寻找什么。在此先感谢您抽出宝贵时间提供帮助!

-Jeff

3 个答案:

答案 0 :(得分:2)

循环键的组合,处理值as sets并打印set difference

for key in pizza_1.keys() | pizza_2:  # union of the dict views
    difference = set(pizza_1.get(key, [])).difference(pizza_2.get(key, []))
    if difference:
        print(key, list(difference))

我在这里使用dict.keys() dictionary view来提供字典键的联合。 if测试过滤掉空结果。

如果您希望将其作为字典,可以使用生成器表达式和字典理解来生成一个字典,以避免多次生成集合:

differences = ((key, list(set(pizza_1.get(key, [])).difference(pizza_2.get(key, []))))
              for key in pizza_1.keys() | pizza_2)
differences = {k: v for k, v in differences if v}

演示:

>>> for key in pizza_1.keys() | pizza_2:  # union of the dict views
...     difference = set(pizza_1.get(key, [])).difference(pizza_2.get(key, []))
...     if difference:
...         print(key, list(difference))
...
crust ['hand tossed']
toppings ['mushroom']
price ['$9.99', '$7.99', '$12.99']
>>> differences = ((key, list(set(pizza_1.get(key, [])).difference(pizza_2.get(key, []))))
...               for key in pizza_1.keys() | pizza_2)
>>> {k: v for k, v in differences if v}
{'crust': ['hand tossed'], 'toppings': ['mushroom'], 'price': ['$9.99', '$7.99', '$12.99']}

答案 1 :(得分:1)

我建议使用set-values作为输出数据结构的字典。

if (isPrime)

结果将为一个键设置一个空集,其中没有区别(见大小)。

答案 2 :(得分:0)

我所做的是循环键并使用列表推导来获得差异(特别是pizza_1中不在pizza_2中的内容,如示例输出所示)。

def getDiff(dict1, dict2):
    diff = {}

    for key in dict1:
        if key not in dict2:
            diff[key] = dict1[key]
        elif dict1[key] != dict2[key]:
            diff[key] = [e for e in dict1[key] if e not in dict2[key]]

    return diff