Was wondering if something like the following was possible:
rarity = {>= 75: 'Common', <= 20 : 'Rare', >= 5: 'Legendary'}
Was wondering if something like the following was possible:
rarity = {>= 75: 'Common', <= 20 : 'Rare', >= 5: 'Legendary'}
In Python 2.7 this will raise a syntax error. It feels like abuse of dictionary (key-value storage) concept. Maybe you should rework your code and you could use 'Common'
, 'Rare'
as keys and values as ranges, i.e. range(5,20)
, range(20)
, etc.
This cannot be done with dict
in python. You probably need an ordinary function for your task:
def check(x):
if x >= 75:
return 'Common'
if x <= 20:
...
Remember that order of checks and return
statements matters.
I can't see a way to do this with better than O(k) performance, where k
is the number of keys in your sort-of dict.
If you are not seeking dict
's O(1) performance, and just want a dict
-like syntax, you can implement a mapping object yourself, like so:
from collections.abc import Mapping
class CallDict(Mapping):
def __init__(self, *pairs):
self._pairs = pairs
def __iter__(self):
return iter(())
def __len__(self):
return len(self._pairs)
def __getitem__(self, x):
for func, value in self._pairs:
if func(x):
return value
raise KeyError("{} satisfies no condition".format(x))
# Conditions copied directly from OP, but probably wrong.
cd = CallDict(
((lambda x: x >= 75), "Common"),
((lambda x: x <= 20), "Rare"),
((lambda x: x >= 5), "Legendary"),
)
assert cd[1] == 'Rare'
assert cd[10] == 'Rare'
assert cd[50] == 'Legendary'
assert cd[100] == 'Common'