UPDATE: Just to be clear, I'd like to check the key-value of the 'name' and 'last' and add only if these are not already in the list.
I have:
lst = [{'name':'John', 'last':'Smith'.... .... (other key-values)... },
{'name':'Will', 'last':'Smith'... ... (other key-values)... }]
I want to append aa new dict into this list only if it is not the exact same as an existing dictionary.
In other words:
dict1 = {'name':'John', 'last':'Smith'} # ==> wouldn't be appended
but...
dict2 = {'name':'John', 'last':'Brown'} # ==> WOULD be appended
Could someone explain the simplest way to do this, as well as in English, what is happening in the solution. THANKS!
Reference: Python: Check if any list element is a key in a dictionary
Since you asked for a way to only check the two keys, even if the dicts have other keys in them:
name_pairs = set((i['name'], i['last']) for i in lst)
if (d['name'], d['last']) not in name_pairs:
lst.append(d)
You can do it with this list comprehension just append everything to your list and run this:
lst.append(dict1)
lst.append(dict2)
[dict(y) for y in set(tuple(x.items()) for x in lst)]
The output is:
[
{'last': 'Smith', 'name': 'John'},
{'last': 'Brown', 'name': 'John'},
{'last': 'Smith', 'name': 'Will'}
]
With this method you can add extra fields and it will still work.
You could also write a small method to do it and return the list
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)
It works by filtering the original list to matching the name and last keys and seeing if the result is empty.
>>> 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}])
Instance of the Person class can be used as simple dict.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.