Python Filter List of Dictionaries Based on Key Value

python filter list of dictionaries based on key value

You can try a list comp

>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Another way is by using filter

>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Filter list of dictionaries from a value and get items forward

Here's a function to walk the list and return all the items after the dictionary containing a certain key/value:

list_ = [{'a': '-1', 'month': 'January'},
{'a': '0', 'month': 'February'},
{'a': '1', 'month': 'March'},
{'a': '2', 'month': 'April'}]

def forward(items,key,value):
# Note: enumerate returns the index and value of each list item
for i,d in enumerate(items):
if d[key] == value: # once the dictionary containing the key/value is found
return list_[i+1:] # return a slice of all items after that index
return []

print(forward(list_,'a','-1'))
print(forward(list_,'a','0'))
print(forward(list_,'a','1'))

Output:

[{'a': '0', 'month': 'February'}, {'a': '1', 'month': 'March'}, {'a': '2', 'month': 'April'}]
[{'a': '1', 'month': 'March'}, {'a': '2', 'month': 'April'}]
[{'a': '2', 'month': 'April'}]

Python: filter list of dictionaries based on multiple key values

The first empty dictionary {} is there because {"pytest_version": "7.1.e", "$report_type": "SessionStart"} doesn't contain key 'label' or 'outcome'.

One solution might be using all() to keep only the dictionaries which contains all keys in the key_list:

logs = [
{"pytest_version": "7.1.e", "$report_type": "SessionStart"},
{"label": "test1", "outcome": "passed", "duration": 0.0009},
{"label": "test2", "outcome": "passed", "duration": 0.00019},
]

key_list = ["label", "outcome"]

print(
[{k: d[k] for k in key_list} for d in logs if all(k in d for k in key_list)]
)

Prints:

[{'label': 'test1', 'outcome': 'passed'}, {'label': 'test2', 'outcome': 'passed'}]

Filter by list of dictionaries by one key and sort by datetime

Combine

  • filter with lambda x: x['action'] == 1 as key
  • sorted with lambda x: x['date'] as key and reversed=True
actions = sorted(filter(lambda x: x['action'] == 1, actions),
key=lambda x: x['date'], reverse=True)

Filtering list of dicts based on a key value in python

You could create a function that gets the public data for children of each entry:

def get_public_data(data):
result = []
children = data.get("children")
if children:
for row in children:
path = row.get("path")
if path and "public" in path:
result.append(row)
return result

And then create a new list of entries where you just replace the children key:

public_list = []
for x in entities:
public_data = get_public_data(x)
if public_data:
public_list.append({**x, "children": public_data})

Combine these two and you'll get the function you need.

Need to filter list of dictionaries

It's fairly straightforward to turn your list into a dictionary that has exactly what you need:

list_of_dict = [
{'label': '220_2_INTL_PRSTR_ET_619076', 'value': '220_2_INTL_PRSTR_ET_619076'},
{'label': '220_4_KAL_T2E_DOLE_344657', 'value': '220_4_KAL_T2E_DOLE_344657'},
{'label': '221_1_PB_520_REF_174049', 'value': '221_1_PB_520_REF_174049'},
{'label': '222_5_KAL_T2E_YT_344991', 'value': '222_5_KAL_T2E_YT_344991'},
{'label': '223_2_PB_520_REF_174050', 'value': '223_2_PB_520_REF_174050'},
{'label': '224_3_PB_520_REF_174051', 'value': '224_3_PB_520_REF_174051'}
]

# it's a "one-liner", a dict comprehension split over a few lines for readability:
result = {
p: [d for d in list_of_dict if d['label'].startswith(p)]
for p in set(d['label'][:3] for d in list_of_dict)
}

print(result['220']) # the contents for this prefix
print(result.keys()) # the keys for your first dropdown

Output:

[{'label': '220_2_INTL_PRSTR_ET_619076', 'value': '220_2_INTL_PRSTR_ET_619076'}, {'label': '220_4_KAL_T2E_DOLE_344657', 'value': '220_4_KAL_T2E_DOLE_344657'}]
['222', '220', '224', '223', '221']

Note that the keys are out of order, but sorting is straightforward.

Instead of d['label'][:3] you could consider d['label'].split('_')[0], if the prefixes aren't all 3 characters long, but instead are "everything before the first underscore".

Edit: in the comments, you asked for some additional explanation of the core bit of code:

{
p: [d for d in list_of_dict if d['label'].startswith(p)]
for p in set(d['label'][:3] for d in list_of_dict)
}
  • Anything of the form {..: .. for .. in ..} is a dictionary comprehension, constructing a dictionary using a very efficient loop.
  • Here it's {p: ... for p in set(d['label'][:3] for d in list_of_dict)}. So, p loops over the elements of set(d['label'][:3] for d in list_of_dict) and for every p, a key is added to the dictionary.
  • That d['label'][:3] for d in list_of_dict is a generator expression that generates the first three characters ([:3]) of every 'label' value for every dictionary d in your list_of_dict. I.e. ['220', '220', '221', '222', etc.]. And the set() around it reduces it to have only unique elements.
  • The value part of the dictionary comprehension is a list comprehension, so a list is construction as a value for each key p. A list comprehension looks like [.. for .. in ..] (with an optional if ..-part to filter the contents)
  • The comprehension [d for d in list_of_dict if d['label'].startswith(p)] takes each dictionary d from your list_of_dict, but only keeps it in the resulting list if d['label'].startswith(p) is True (i.e. only if d['label'] starts with p, which is the current 3-letter string being used as a key.

So, it gathers all of the 3-letter prefixes in a set, and then generates a dictionary with those unique prefixes as keys, and a list of all the dictionaries that have 'label' values starting with the matching 3-letter prefix, as their value.

Filter list of dictionaries by value and then add other keys & values to filtered dictionary?

option_list_dict = [{'strike_price': '1', 'bid_price': '0.25', 'delta': '0.94' }, 
{'strike_price': '1.5', 'bid_price': '0.15', 'delta': '0.88'},
{'strike_price': '2', 'bid_price': '0.05', 'delta': 'None'},
{'strike_price': '2.5', 'bid_price': '0.31', 'delta': '0.25'}]

result = []

for dict in option_list_dict:
try:
if float(dict['delta']) > 0.9:
result.append(dict)
except:
pass

print(result)

This approach returns a list of all the dictionaries that satisfy the condition, in this case:

result = [{'strike_price': '1', 'bid_price': '0.25', 'delta': '0.94'}]

Filter a list of dictionaries in Python based on key

l = [{u'id': 5650, u'children': [{u'id': 4635}]}, {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}, {u'id': 5649}]
d = [k for k in l if 'children' in k]
print (d)

Outputs:

[{u'id': 5650, u'children': [{u'id': 4635}]}, {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}]

The important line is the second line (d = ...). This is looping through each dictionary in the list and checking if there is a 'children' key. If there is, it is added to the list. If there is not, it's skipped.



Related Topics



Leave a reply



Submit