0

(Python) Dictionary divided into two based on a property

 2 years ago
source link: https://www.codesd.com/item/python-dictionary-divided-into-two-based-on-a-property.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

(Python) Dictionary divided into two based on a property

advertisements

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.


One line solution (with lower_excluded_users which I couldn't resist making)

included, excluded = dict(), dict()

# ssly, you don't have to do this everytime
lower_excluded_users = [x.lower() for x in EXCLUDED_USERS]

# and now the one-line answer using if-else-for construct with
# v substituted by D[k]. And instead of using `for k, v in dicn.items()`
# I have used [... for aKey in dicn.keys()]

[ excluded.update({aKey: users[aKey]}) \
    if any(x in users[aKey]["name"].lower() for x in lower_excluded_users) \
    else \
    included.update({aKey: users[aKey]}) \
    for aKey in users.keys()
]

Or one without beautification:

[excluded.update({aKey: users[aKey]}) if any(x in users[aKey]["name"].lower() for x in lower_excluded_users) else included.update({aKey: users[aKey]}) for aKey in users.keys()]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK