【问题标题】:python - list of dictionaries check key:valuepython - 字典列表检查键:值
【发布时间】:2012-06-27 03:29:58
【问题描述】:

更新:为了清楚起见,我想检查 'name' 和 'last' 的键值,并仅在它们不在列表中时添加。

我有:

lst = [{'name':'John', 'last':'Smith'.... .... (other key-values)... }, 
{'name':'Will', 'last':'Smith'... ... (other key-values)... }]

只有当它与现有字典不完全相同时,我才想将一个新字典附加到此列表中。

换句话说:

dict1 = {'name':'John', 'last':'Smith'} # ==> wouldn't be appended

但是……

dict2 = {'name':'John', 'last':'Brown'} # ==> WOULD be appended

谁能解释一下最简单的方法,以及用英语解释解决方案中发生的事情。谢谢!

参考:Python: Check if any list element is a key in a dictionary

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    由于您要求一种仅检查两个键的方法,即使字典中有其他键:

    name_pairs = set((i['name'], i['last']) for i in lst)
    if (d['name'], d['last']) not in name_pairs:
        lst.append(d)
    

    【讨论】:

    • 我可能会为大量的 dicts 执行此操作。有没有办法优化不必每次都创建 name_pairs?
    • 好吧,您可以在更改字典时维护该集合。或者,您可以使用以(first,last) 为关键字的字典,而不是使用列表并附加到它。
    【解决方案2】:

    您可以使用此列表推导来做到这一点,只需将所有内容附加到您的列表并运行:

    lst.append(dict1)
    lst.append(dict2)
    [dict(y) for y in set(tuple(x.items()) for x in lst)]
    

    输出是:

    [
        {'last': 'Smith', 'name': 'John'},
        {'last': 'Brown', 'name': 'John'},
        {'last': 'Smith', 'name': 'Will'}
    ]
    

    使用此方法,您可以添加额外的字段,它仍然可以工作。

    【讨论】:

      【解决方案3】:

      您也可以编写一个小方法来执行此操作并返回列表

      def update_if_not_exist(lst, val):
          if len([d for d in lst if (d['name'], d['last']) == (val['name'], val['last'])]) == 0:
              lst.append(val)
          return lst
      
      lst = update_if_not_exist(lst, dict1)
      lst = update_if_not_exist(lst, dict2)
      

      它通过过滤原始列表以匹配名称和最后一个键并查看结果是否为空来工作。

      【讨论】:

        【解决方案4】:
        >>> class Person(dict):
        ...     def __eq__(self, other):
        ...         return (self['first'] == other['first'] and
        ...                 self['second'] == other['second'])
        ...     def __hash__(self):
        ...         return hash((self['first'], self['second']))
        
        >>> l = [{'first': 'John', 'second': 'Smith', 'age': 23},
        ...         {'first': 'John', 'second': 'Smith', 'age': 30},
        ...         {'first': 'Ann', 'second': 'Rice', 'age': 31}]
        
        >>> l = set(map(Person, l))
        >>> print l
        set([{'first': 'Ann', 'second': 'Rice', 'age': 31},
            {'first': 'John', 'second': 'Smith', 'age': 23}])
        

        Person 类的实例可以用作简单的字典。

        【讨论】:

          猜你喜欢
          • 2020-08-05
          • 2019-04-19
          • 1970-01-01
          • 2014-03-14
          • 2022-11-29
          • 2016-11-14
          • 2022-10-14
          • 2016-09-29
          • 1970-01-01
          相关资源
          最近更新 更多