Rodrigo
Rodrigo

Reputation: 381

One-liner to calculate the score based on two dicts

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

Answers (6)

Maurice Meyer
Maurice Meyer

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

bb1
bb1

Reputation: 7873

sum([scores[k]*data.get(k, False) for k in scores])

Upvotes: 2

Adarsh TS
Adarsh TS

Reputation: 303

You can do this:

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

Upvotes: 0

Unapiedra
Unapiedra

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

Anson Miu
Anson Miu

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

Timur Shtatland
Timur Shtatland

Reputation: 12377

Use list comprehension:

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

Upvotes: 2

Related Questions