

(Python) Dictionary divided into two based on a property
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
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()]
Recommend
-
173
Kotlin Programmer Dictionary: Field vs Property
-
19
So... Do I Edit Blog Posts or Not? Paolo Says NO. Alex Says YES. I'm Divided. Aug 7, 2002 So... Do I Edit Blog Posts or Not? Paolo Says NO. Alex Says YES. I'm Divided. Last updated: 8/7/2002; 9:06:34 AM...
-
10
钱该放哪儿? - COVID-19 - II 三个世界 Divided We Survive牛意思智有所不明,人有所不持
-
8
Delphi 2010 Code Formatter: & ldquo; (MyVar as TMyType) .MyMethod & rdquo; is divided into two lines advertisements How to prevent the...
-
12
Expert panel divided over best way to achieve diversity in crypto sector – HodlalertExpert panel divided over best way to achieve diversity in crypto sector...
-
10
MathWhy is a minute divided into 60 seconds, an hour into 60 minutes, yet there are only 24 hours in a day? Credit:
-
11
Improve Article Check if a given array can be divided into pairs with even sumDifficulty Level : ExpertLast Updated : 28 Apr, 2021...
-
16
Afiz Posted on Jan 2...
-
8
Francis T. O'Donovan Data Science Manager at LeanTaaS – Planet discoverer, researcher, developer, ge...
-
7
SE Radio 589: Zac Hatfi...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK