I've got a Python list of dictionaries, as follows:
我有一个Python字典列表,如下所示:
a = [
{'main_color': 'red', 'second_color':'blue'},
{'main_color': 'yellow', 'second_color':'green'},
{'main_color': 'yellow', 'second_color':'blue'},
]
I'd like to check whether a dictionary with a particular key/value already exists in the list, as follows:
我想检查列表中是否已存在具有特定键/值的字典,如下所示:
// is a dict with 'main_color'='red' in the list already?
// if not: add item
3 个解决方案
#1
149
Here's one way to do it:
这是一种方法:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
The part in parentheses is a generator expression that returns True
for each dictionary that has the key-value pair you are looking for, otherwise False
.
括号中的部分是一个生成器表达式,它为具有您要查找的键值对的每个字典返回True,否则返回False。
If the key could also be missing the above code can give you a KeyError
. You can fix this by using get
and providing a default value.
如果密钥也可能丢失,上面的代码可以给你一个KeyError。您可以使用get并提供默认值来解决此问题。
if not any(d.get('main_color', None) == 'red' for d in a):
# does not exist
#2
4
Maybe this helps:
也许这有助于:
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 this in my_dictlist:
if this[key] == value:
return this
return {}
print in_dictlist(('main_color','red'), a)
print in_dictlist(('main_color','pink'), a)
#3
2
Perhaps a function along these lines is what you're after:
也许沿着这些方向的功能就是你所追求的:
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
#1
149
Here's one way to do it:
这是一种方法:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
The part in parentheses is a generator expression that returns True
for each dictionary that has the key-value pair you are looking for, otherwise False
.
括号中的部分是一个生成器表达式,它为具有您要查找的键值对的每个字典返回True,否则返回False。
If the key could also be missing the above code can give you a KeyError
. You can fix this by using get
and providing a default value.
如果密钥也可能丢失,上面的代码可以给你一个KeyError。您可以使用get并提供默认值来解决此问题。
if not any(d.get('main_color', None) == 'red' for d in a):
# does not exist
#2
4
Maybe this helps:
也许这有助于:
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 this in my_dictlist:
if this[key] == value:
return this
return {}
print in_dictlist(('main_color','red'), a)
print in_dictlist(('main_color','pink'), a)
#3
2
Perhaps a function along these lines is what you're after:
也许沿着这些方向的功能就是你所追求的:
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