Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Python) Split dictionary in two based on a property

I want to split a dictionary in two based on whether any of an array of strings is present in a property within the main dictionary. Currently I can achieve this with two separate dictionary comprehensions (below), but is there a more efficient way to do this with only one line/dictionary comprehension?

included = {k:v for k,v in users.items() if not any(x.lower() in v["name"].lower() for x in EXCLUDED_USERS)}
excluded = {k:v for k,v in users.items() if any(x.lower() in v["name"].lower() for x in EXCLUDED_USERS)}

EDIT

EXCLUDED_USERS contains a list of patterns.

like image 905
ryansin Avatar asked Oct 19 '25 15:10

ryansin


1 Answers

This solution is more verbose, but it should be more efficient and possibly more readable:

included = {}
excluded = {}

lower_excluded_users = [x.lower() for x in EXCLUDED_USERS]

for k,v in users.items():
    if any(x in v["name"].lower() for x in lower_excluded_users):
        excluded[k] = v
    else:
        included[k] = v

I don't think it can be done with one single comprehension. It's possible to use a ternary operator inside the k:v statement, it's not possible to use else after the if in a {k:v for k,v in users.items() if k ...} pattern.

like image 142
Eric Duminil Avatar answered Oct 21 '25 04:10

Eric Duminil