One-liner to calculate the score based on two dicts

Viewed 124

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
6 Answers
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.

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

Use list comprehension:

score = sum([scores[k] for k in scores.keys() if data[k]])
print(score)
# 500

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)
sum([scores[k]*data.get(k, False) for k in scores])

You can do this:

score += sum([a*b for a, b in zip(scores.values(), data.values())])
Related