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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With