I want to create a dict which can be accessed as:
d[id_1][id_2][id_3] = amount
As of now I have a huge ugly function:
def parse_dict(id1,id2,id3,principal, data_dict):
if data_dict.has_key(id1):
values = data_dict[id1]
if values.has_key[id2]
..
else:
inner_inner_dict = {}
# and so on
What is the pythonic way to do this?
note, that i input the principal.. but what i want is the amount.. So if all the three keys are there.. add principal to the previous amount!
Thanks
You may want to consider using defaultdict
:
For example:
json_dict = defaultdict(lambda: defaultdict(dict))
will create a defaultdict
of defaultdict
s of dict
s (I know..but it is right), to access it, you can simply do:
json_dict['context']['name']['id'] = '42'
without having to resort to using if...else
to initialize.
from collections import defaultdict
d = defaultdict(lambda : defaultdict(dict))
d[id_1][id_2][id_3] = amount
You can make a simple dictionary that creates new ones (using Autovivification):
>>> class AutoDict(dict):
def __missing__(self, key):
x = AutoDict()
self[key] = x
return x
>>> d = AutoDict()
>>> d[1][2][3] = 4
>>> d
{1: {2: {3: 4}}}
This will have no limit of dimensions as the defaultdict with dict has.
Or a simpler version using defaultdict
(from the above wiki link):
def auto_dict():
return defaultdict(auto_dict)
>>> from collections import defaultdict
>>> import json
>>> def tree(): return defaultdict(tree)
>>> t = tree()
>>> t['a']['b']['c'] = 'foo'
>>> t['a']['b']['d'] = 'bar'
>>> json.dumps(t)
'{"a": {"b": {"c": "foo", "d": "bar"}}}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With