Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python generating nested dictionary key error

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': ''...}
    }
}
like image 387
user3071933 Avatar asked Sep 05 '25 02:09

user3071933


2 Answers

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'
like image 166
user2390183 Avatar answered Sep 07 '25 15:09

user2390183


result = {}
result['data'] = {}

for i, q in enumerate(query):
    result['data']['i'] = {}
    result['data'][i]['firstName'] = q.first_name
    result['data'][i]['lastName'] = q.last_name
    result['data'][i]['email'] = q.email

Alternatively, you can use you own class which adds the extra dicts automatically

class AutoDict(dict):
    def __missing__(self, k):
        self[k] = AutoDict()
        return self[k]

result = AutoDict()

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
like image 43
John La Rooy Avatar answered Sep 07 '25 15:09

John La Rooy