python generating nested dictionary key error
dictionary, python
Solution
You wanted to create a nested dictionary
`result = {}` will create an assignment for a flat dictionary, whose items can have any values like "string", "int", "list" or "dict"
For this flat assignment
python knows what to do for `result["first"]`
If you want "first" also to be another dictionary you need to tell Python by an assingment `result['first'] = {}`.
otherwise, Python raises `"KeyError"`
I think you are looking for this :)
>>> from collections import defaultdict
>>> mydict = lambda: defaultdict(mydict)
>>> result = mydict()
>>> result['Python']['rules']['the world'] = "Yes I Agree"
>>> result['Python']['rules']['the world']
'Yes I Agree'
Problem
I am trying to create a nested dictionary from a mysql query but I am getting a key error ``` result = {} for i, q in enumerate(query): result['data'][i]['firstName'] = q.first_name result['data'][i]['lastName'] = q.last_name result['data'][i]['email'] = q.email ``` error ``` KeyError: 'data' ``` desired result ``` result = { 'data': { 0: {'firstName': ''...} 1: {'firstName': ''...} 2: {'firstName': ''...} } } ```