我有一个Python字典列表,如下所示:
a = [
{'main_color': 'red', 'second_color':'blue'},
{'main_color': 'yellow', 'second_color':'green'},
{'main_color': 'yellow', 'second_color':'blue'},
]
我想检查列表中是否已经存在具有特定键/值的字典,如下所示:
// is a dict with 'main_color'='red' in the list already?
// if not: add item
发布于 2010-10-10 03:40:01
也许这会有帮助:
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
def in_dictlist(key, value, my_dictlist):
for entry in my_dictlist:
if entry[key] == value:
return entry
return {}
print in_dictlist('main_color','red', a)
print in_dictlist('main_color','pink', a)
发布于 2010-10-10 03:21:53
也许你想要的就是下面这样的一个函数:
def add_unique_to_dict_list(dict_list, key, value):
for d in dict_list:
if key in d:
return d[key]
dict_list.append({ key: value })
return value
发布于 2019-10-20 05:20:30
基于@Mark Byer的很好的答案,并遵循@Florent问题,只是为了表明它也适用于具有超过2个键的dics列表中的2个条件:
names = []
names.append({'first': 'Nil', 'last': 'Elliot', 'suffix': 'III'})
names.append({'first': 'Max', 'last': 'Sam', 'suffix': 'IX'})
names.append({'first': 'Anthony', 'last': 'Mark', 'suffix': 'IX'})
if not any(d['first'] == 'Anthony' and d['last'] == 'Mark' for d in names):
print('Not exists!')
else:
print('Exists!')
结果:
Exists!
https://stackoverflow.com/questions/3897499
复制相似问题