简体   繁体   中英

How to access both range and strings in the same dictionary?

I have a dictionary with following

check = RangeDict({{
range(10, 100): 40,
range(110, 115): 40,
range(118, 121): 50,
range(130, 131): 50,
range(140, 141): 30
}

and I access the value with the following

class RangeDict(dict):
    def __getitem__(self, item):
        if not isinstance(item, range):  
            for key in self:
                if item in key:
                    return self[key]
            raise KeyError(item)
        else:
             return super().__getitem__(item)  

id =  199
print(check[id])

I need my dictionary to also include

{
range(10, 100): 40,
range(110, 115): 40,
range(118, 121): 50,
range(130, 131): 50,
range(140, 141): 30,
"a100": 110,
"c120": 100
}

Is this possible if using range for the integers and to also include string: values and how can I change function to read string

RecursionError: maximum recursion depth exceeded while calling a Python object

Just,

check = {
range(10, 100): 40,
range(110, 115): 40,
range(118, 121): 50,
range(130, 131): 50,
range(140, 141): 30,
"a100": 110,
"c120": 100
}

This is stored as :

{range(10, 100): 40,
 range(110, 115): 40,
 range(118, 121): 50,
 range(130, 131): 50,
 range(140, 141): 30,
 'a100': 110,
 'c120': 100}

And then to access,

a = check[range(10,100)]

Which gives:

40

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM