defaultdict, :
mapfile = collections.defaultdict(int, mapfile)
:
mapfile = collections.defaultdict(int, {
1879048192: 0,
1879048193: 0,
1879048194: 0,
1879048195: 0,
1879048196: 4,
1879048197: 3,
1879048198: 2,
1879048199: 17,
1879048200: 0,
1879048201: 1,
1879048202: 0,
1879048203: 0,
1879048204: 4,
1879048206: 2,
1879048207: 1,
1879048208: 0 # single byte cannot make up a dword
})
print(mapfile[1879048205]) # -> 0
print(mapfile['bogus']) # -> 0
Another alternative is to derive your own class. To implement a class like a dictionary, you don’t need a lot of additional code, which not only provided values for the missing keys, for example, defaultdictdo, but also checked a little check on them. Here is an example of what I mean - the dict-like class , which only accepts missing keys if they are an integer, and not just something like normal defaultdict:
import numbers
class MyDefaultIntDict(dict):
default_value = 0
def __missing__(self, key):
if not isinstance(key, numbers.Integral):
raise KeyError('{!r} is an invalid key'.format(key))
self[key] = self.default_value
return self.default_value
mapfile = MyDefaultIntDict({
1879048192: 0,
1879048193: 0,
1879048194: 0,
1879048195: 0,
1879048196: 4,
1879048197: 3,
1879048198: 2,
1879048199: 17,
1879048200: 0,
1879048201: 1,
1879048202: 0,
1879048203: 0,
1879048204: 4,
1879048206: 2,
1879048207: 1,
1879048208: 0 # single byte cannot make up a dword
})
print(mapfile[1879048205]) # -> 0
print(mapfile['bogus']) # -> KeyError: "'bogus' is an invalid key"