Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dictionary to default dictionary python?

mapfile = {
    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,
    # intentionally missing byte
    1879048206: 2,
    1879048207: 1,
    1879048208: 0 # single byte cannot make up a dword
}

_buf = {}
for x in (x for x in mapfile.keys() if 0==x%4):
    try:
        s = "0x{0:02x}{1:02x}{2:02x}{3:02x}".format(mapfile[x+3], mapfile[x+2],
                                                    mapfile[x+1], mapfile[x+0])
        print "offset ", x, " value ", s
        _buf[x] = int(s, 16)
    except KeyError as e:
        print "bad key ", e

    print "_buf is ", _buf

Since I am using dictionary, I am getting KeyError. Plan is to make dictionary as defaultdict(int) so that in default dictionary it will pad zero when there is KeyError. But I didn't find any solution. How I can convert dictionary to default dictionary?

like image 624
Sandy Avatar asked Jul 23 '15 08:07

Sandy


3 Answers

You can convert a dictionary to a defaultdict:

>>> a = {1:0, 2:1, 3:0}
>>> from collections import defaultdict
>>> defaultdict(int,a)
defaultdict(<type 'int'>, {1: 0, 2: 1, 3: 0})
like image 77
Vlad Avatar answered Sep 21 '22 20:09

Vlad


Instead of re-creating the dictionary, you can use get(key, default). key is the key that you want to retrieve and default is the value to be returned if the key isn't in the dictionary:

my_dict = { }
print my_dict.get('non_existent_key', 0)
>> 0
like image 30
DeepSpace Avatar answered Sep 20 '22 20:09

DeepSpace


I think, KeyError can be solved here by setting 0 as default value.

In [5]: mydict = {1:4}

In [6]: mydict.get(1, 0)
Out[6]: 4

In [7]: mydict.get(2, 0)
Out[7]: 0

Hope this helps. You can change your code to something like mapfile.get([x+3], 0).

OR

from collections import defaultdict
mydict = {1:4}
mydefaultdict = defaultdict(int, mydict)
>>>mydefaultdict[1]
4
>>>mydefaultdict[2]
0
like image 44
itzMEonTV Avatar answered Sep 18 '22 20:09

itzMEonTV