【问题标题】:Compare dictionaries within lists python比较列表中的字典python
【发布时间】:2017-12-19 19:18:22
【问题描述】:

我有两个带有嵌套字典的列表:

list1 = [{u'Key': u'lm_app', u'Value': u'lm_app'}, {u'Key': u'Name', u'Value': u'new Name'}, {u'Key': u'lm_sbu', u'Value': u'lm_sbu'}, {u'Key': u'lm_app_env', u'Value': u'lm_app_env'}]

list 2 = [{u'Key': 'lm_sbu', u'Value': 'lm_sbu'}, {u'Key': 'Name', u'Value': 'test'}]

如何检查列表 1 中的键是否存在于列表 2 中?

关于这个例子,键 'lm_sbu' 和 'Name' 都存在于列表 1 和列表 2 中。但是键 'lm_app' 和 'lm_app_env' 存在于列表 1 中,但不存在于列表 2 中。

一旦发现差异,我想将差异附加到单独的列表中。

谢谢

【问题讨论】:

    标签: python list dictionary compare keyvaluepair


    【解决方案1】:

    您实际上是在检查值(而不是键)之间的差异,在这种情况下,您可以将 list1 中的字典值与 list2 中的字典值设置差异:

    s = {v for d in list1 for v in d.values()}.difference(*[d.values() for d in list2])
    print s
    # set([u'new Name', u'lm_app', u'lm_app_env'])
    

    【讨论】:

      【解决方案2】:

      类似这样,您在 itemlist 中搜索的项目。使用库有更短的方法来做到这一点,但我喜欢 vanilla python。

      a = [i for j in [l.items() for l in list2] for i in j]
      print "\n".join(filter(lambda item: item in a, itemlist))
      

      【讨论】:

        【解决方案3】:

        Python 集对此有帮助:

        list1 = [{u'Key': u'lm_app', u'Value': u'lm_app'}, {u'Key': u'Name', u'Value': u'new Name'}, {u'Key': u'lm_sbu', u'Value': u'lm_sbu'}, {u'Key': u'lm_app_env', u'Value': u'lm_app_env'}]
        list2 = [{u'Key': 'lm_sbu', u'Value': 'lm_sbu'}, {u'Key': 'Name', u'Value': 'test'}]
        
        list1_keys = {dictionary['Key'] for dictionary in list1}
        list2_keys = {dictionary['Key'] for dictionary in list2}
        
        print 'Keys in list 1, but not list 2: {}'.format(list(list1_keys - list2_keys))
        print 'Keys in list 2, but not list 1: {}'.format(list(list2_keys - list1_keys))
        

        输出:

        Keys in list 1, but not list 2: [u'lm_app', u'lm_app_env']
        Keys in list 2, but not list 1: []
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多