【问题标题】:Compare two dictionaries and check if some values do not exist [duplicate]比较两个字典并检查某些值是否不存在[重复]
【发布时间】:2021-12-14 20:58:26
【问题描述】:

我有两个字典列表如下:

string1 =[
  {"name": "Tom", "age": 10},
  {"name": "Mark", "age": 5},
  {"name": "Pam", "age": 7},
  {"name": "Weranika", "age": 18}
]
string2 =[  {"name": "Tom", "age": 8},
  {"name": "Mark", "age": 5},
  {"name": "Pam", "age": 7}
]

我想打印第二个字典列表中不存在的项目的键/值。

在我的情况下,输出应该返回:

{"name": "Weranika", "age": 18}

【问题讨论】:

  • 你试过什么?请告诉我们。
  • 你可以遍历字典看看是否匹配
  • 我没有downvote your question because no attempt was made,因为您是新贡献者,但通常我们希望您至少创建一个honest attempt at the solution,然后然后提出具体问题( s) 关于你的实施。
  • Tom,每个列表中的年龄不同,你想做什么?
  • 对不起,忘了说明,我需要考虑这样的结果,其中只有 key = "name" 的值不存在于第二个 dict 列表中。

标签: python dictionary


【解决方案1】:

您可以遍历string1 中的字典并检查其中的名称是否存在于string2 中的名称集中:

names = set(d['name'] for d in string2)
not_in_string2 = [dct for dct in string1 if dct['name'] not in names]

输出:

{'name': 'Weranika', 'age': 18}

【讨论】:

    【解决方案2】:
    def compare(list_dict_1, list_dict_2):
        return [item for item in list_dict_1 if item not in list_dict_2]
            
    

    【讨论】:

    • 应该是...if item not in...
    • 对不起,忘了说明,我需要考虑这样的结果,其中只有 key = "name" 的值不存在于第二个 dict 列表中。
    【解决方案3】:
    str1  = [i["name"] for i in string1]
    

    获取字符串中的名称

    str2  = [i["name"] for i in string2]
    

    名称不在 string2 中,而是在 1 中

    not_in_string_2 = list(set(str1) ^ set(str2))
    

    不在 sring2 中的值的索引

    index = []
    for x,i in enumerate(string1):
        if i["name"] in not_in_string_2:
            index.append(x)
    for i in index:
       print(string1[i])
    

    打印结果

    【讨论】:

      【解决方案4】:

      即使列表的顺序不同,此方法也可以工作:

      首先,我们需要做一些处理,将每个字典变成一个不可变对象。这样我们就可以将它们添加到 set,这是一个未排序的容器,允许快速成员资格检查以及其他功能。

      processed_string1 = set((d["name"], d["age"]) for d in string1)
      processed_string2 = set((d["name"], d["age"]) for d in string2)
      

      然后我们可以使用setdifference方法获取第一组中的项目,而不是第二组:

      result_set = processed_string1.difference(processed_string2)
      

      然后我们只需要转换回字典:

      result_list = [{"name": t[0], "age": t[1]} for t in result_set]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-22
        • 2021-09-14
        • 1970-01-01
        相关资源
        最近更新 更多