The way I go about nested dictionary is this:
dicty = dict()
tmp = dict()
tmp[\"a\"] = 1
tmp[\"b\"] = 2
dicty[\"A\"] = tmp
dicty == {\"A\" : {\"a\" : 1, \"b
Use a collections.defaultdict() object to auto-instantiate nested dictionaries:
from collections import defaultdict
def doubleDict(filename):
dicty = defaultdict(dict)
with open(filename, "r") as f:
for i, line in enumerate(f):
outer, inner, value = line.split()
dicty[outer][inner] = value
if i % 25 == 0:
print(dicty)
break #print(row)
return(dicty)
I used enumerate()
to generate the line count here; much simpler than keeping a separate counter going.
Even without a defaultdict
, you can let the outer dictionary keep the reference to the nested dictionary, and retrieve it again by using values[0]
; there is no need to keep the temp
reference around:
>>> dicty = {}
>>> dicty['A'] = {}
>>> dicty['A']['a'] = 1
>>> dicty['A']['b'] = 2
>>> dicty
{'A': {'a': 1, 'b': 1}}
All the defaultdict
then does is keep us from having to test if we already created that nested dictionary. Instead of:
if outer not in dicty:
dicty[outer] = {}
dicty[outer][inner] = value
we simply omit the if
test as defaultdict
will create a new dictionary for us if the key was not yet present.