我正在尝试从mysql查询创建嵌套字典,但是我收到了一个关键错误
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
错误
KeyError: 'data'
期望的结果
result = {
'data': {
0: {'firstName': ''...}
1: {'firstName': ''...}
2: {'firstName': ''...}
}
}
答案 0 :(得分:3)
您想要创建嵌套词典
result = {}将为平面字典创建一个赋值,其字符可以包含任何值,如“string”,“int”,“list”或“dict”
对于这个单位作业
python知道该怎么做结果[“first”]
如果你想要“第一个”也是另一个字典,你需要通过一个assing来告诉Python 结果['first'] = {}。
否则,Python会引发“KeyError”
我认为你正在寻找这个:)
>>> 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'
答案 1 :(得分:0)
result['data']
确实存在。所以你无法向它添加数据。
一开始就试试这个:
result = {'data': []};
答案 2 :(得分:0)
您必须先创建密钥data
:
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
答案 3 :(得分:0)
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
或者,您可以使用自己的类,自动添加额外的词组
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