Reputation: 381
I have the following table of values:
scores = {
"proxy": 300,
"vpn": 500,
"tor": 900,
"recent_abuse": 1000,
}
And this data with booleans
data = {
"proxy": False,
"vpn": True,
"tor": False,
"recent_abuse": False,
}
What I want is to know if it possible to calculate in a single line (probably using itertools) a score based on data
My current code is this:
if data["proxy"]:
score += 300
if data["vpn"]:
score += 500
if data["tor"]:
score += 900
if data["recent_abuse"]:
score += 1000
Upvotes: 4
Views: 134
Reputation: 18126
You could use a list generator:
scores = {
"proxy": 300,
"vpn": 500,
"tor": 900,
"recent_abuse": 1000,
}
data = {
"proxy": False,
"vpn": True,
"tor": False,
"recent_abuse": False,
}
score = sum(scores[x] for x in scores if data.get(x, False))
print(score)
Out:
500
Upvotes: 5
Reputation: 303
You can do this:
score += sum([a*b for a, b in zip(scores.values(), data.values())])
Upvotes: 0
Reputation: 16217
total = sum(scores[k] for k, v in data.items() if v)
Better names for k
: field_name
. v
: field_value
.
I derived it in this way:
total = 0
for k, v in data.items():
if v:
total += scores[k]
And from there it is easy to fold it into a single line.
Upvotes: 9
Reputation: 1171
Use a list comprehension to get the scores to add, then sum them up.
score += sum(scores[flag] for flag, enabled in result.items() if enabled)
Upvotes: 2
Reputation: 12377
Use list comprehension:
score = sum([scores[k] for k in scores.keys() if data[k]])
print(score)
# 500
Upvotes: 2