python - 字典列表check key:value

时间:2012-06-27 03:29:58

标签: python list dictionary

更新:为了清楚起见,我想查看'名称'的关键值。并且'最后'并且仅在列表中尚未添加时添加。

我有:

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

我想在这个列表中添加一个新的dict,只要它与现有字典不完全相同。

换句话说:

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

4 个答案:

答案 0 :(得分:4)

由于您要求只检查两个密钥的方法,即使这些密钥中包含其他密钥:

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

答案 1 :(得分:0)

您可以使用此列表理解来执行此操作,只需将所有内容附加到列表中并运行:

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'}
]

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

答案 2 :(得分:0)

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

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)

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

答案 3 :(得分:0)

>>> 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类的实例可以用作简单的dict。

相关问题