Check If Value Already Exists Within List of Dictionaries

Check if value already exists within list of dictionaries?

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.


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. If you don't provide a default value, None is returned.

if not any(d.get('main_color', default_value) == 'red' for d in a):
# does not exist

Check if value already exists within list of dictionaries and if it does update the counter

If you need your data to be in the format you show, and don't want to incur the cost of iterating over that list for every addition, that's not a problem. All you have to do is build an index for that data structure. The index will be a map with keys that are colors and values that are the index of that color in your original structure. You build this index first, and then you use it to process new entries efficiently. Here's how that goes:

colour_dict = [
{'main_colour': 'red', 'count': 1},
{'main_colour': 'blue', 'count': 5},
{'main_colour': 'green', 'count': 10},
]

colours = ["blue", "blue", "red", "greed", "red", "black"]

# Build an index mapping colors to positions in the 'colour_dict' list
index = {}
for i, entry in enumerate(colour_dict):
index[entry['main_colour']] = i

# Iterate over the new values, tallying them in the original structure, and
# adding new entries to both the original structure and the index when
# we discover colors that aren't yet in our structure. Note that there
# is just a single lookup per addition to the structure. No per-addition
# iteration here.
for colour in colours:
if colour in index:
colour_dict[index[colour]]['count'] += 1
else:
index[colour] = len(colour_dict)
colour_dict.append({'main_colour': colour, 'count': 1})

# Show the updated original structure
print(colour_dict)

Result:

[
{'main_colour': 'red', 'count': 3},
{'main_colour': 'blue', 'count': 7},
{'main_colour': 'green', 'count': 10},
{'main_colour': 'greed', 'count': 1},
{'main_colour': 'black', 'count': 1}
]

I am a teacher of programming, and I think this question is an opportunity to highlight an often overlooked technique. You don't have to change your existing data structure that isn't efficient to look things up in to be able to look things up in it efficiently. You can rather build an index into that structure that is efficient to look things up in that points back to the original structure for storage. This is a sort of "have your cake and eat it too" situation. It's worth grasping so you can have it in your bag of tricks.

This is like maintaining an index at the back of a book rather than restructuring the book's content to be easier to search for individual concepts at the cost of making it less valuable to read from front to back. A book index likewise gives you the best of both worlds.

How to check if a value is present in a list of dictionaries?

I think you can do it like this using filter:

permissions = request.session['permissions']
exists = list(filter(lambda x: x.get('mykey') == 'value4', permissions)) # for python 3

# for python2
# exists = filter(lambda x: x.get('mykey') == 'value4', permissions)

if len(exists) > 0:
print('value4 exists')

How to check Key/Value exists in List of Dictionary in Python?

This works by gathering url of each item in data['data'] and seeing if the desired value is in it; it assumes every item in data['data'] has a url element.

"/Province/?ID=83" in [x['url'] for x in data['data']]

Check if key is present in list of dictionaries and if true return dictionary index in list

Hope it helps:

new_list = []
for item in your_dictionaries:
if "tag" in item.keys():
if item["tag"]["member"][0] == "staging-automator":
new_list.append(item)
print(new_list)

How can I check if key exists in list of dicts in python?

I'd probably write:

>>> lod = [{1: "a"}, {2: "b"}]
>>> any(1 in d for d in lod)
True
>>> any(3 in d for d in lod)
False

although if there are going to be a lot of dicts in this list you might want to reconsider your data structure.

If you want the index and/or the dictionary where the first match is found, one approach is to use next and enumerate:

>>> next(i for i,d in enumerate(lod) if 1 in d)
0
>>> next(d for i,d in enumerate(lod) if 1 in d)
{1: 'a'}
>>> next((i,d) for i,d in enumerate(lod) if 1 in d)
(0, {1: 'a'})

This will raise StopIteration if it's not there:

>>> next(i for i,d in enumerate(lod) if 3 in d)
Traceback (most recent call last):
File "<ipython-input-107-1f0737b2eae0>", line 1, in <module>
next(i for i,d in enumerate(lod) if 3 in d)
StopIteration

If you want to avoid that, you can either catch the exception or pass next a default value like None:

>>> next((i for i,d in enumerate(lod) if 3 in d), None)
>>>

As noted in the comments by @drewk, if you want to get multiple indices returned in the case of multiple values, you can use a list comprehension:

>>> lod = [{1: "a"}, {2: "b"}, {2: "c"}]
>>> [i for i,d in enumerate(lod) if 2 in d]
[1, 2]

Removing a key in a list of dictionary with if value condition in python

you can try:

Data = [{key: value for key, value in entry.items() if value != "N/A"} for entry in Data]


Related Topics



Leave a reply



Submit