简体   繁体   English

Python无法从字典列表中创建字典

[英]Python cant make dictionary from list of dictionaries

I have list of dictionaries as a result of django formset error: 由于django formset错误,我有字典列表:

[{}, {"field": ["This field is required."]}, {"field": ["This field is required."]}]

I want to make a dictionary where key is index of dictionary + name of field and value is error message: 我想制作一个字典,其中的键是字典的索引+字段名,值是错误消息:

err = formset.errors
for dict in err:
    for error in dict:
        results[str(err.index(dict))+'-'+error] = dict[error]

Problem is that I get only one value from err, not all. 问题是我从err中仅获得一个值,而不是全部。 How can I solve that? 我该如何解决? Thanks 谢谢

You were pretty close. 你很近。 First I would use enumerate because that what it meant to do. 首先,我将使用枚举,因为这意味着要执行的操作。 And use iteritems(python 2.7) to iterate over the dict.: 并使用iteritems(python 2.7)遍历字典。

for idx, _dict in enumerate(err):
    for error_key, error_value in _dict.iteritems():
        results[str(idx)+'-' + error_key] = error_value

print results

and I got: 我得到:

{'1-field': ['This field is required.'], '2-field': ['This field is required.']} {'1-field':['此字段为必填。',''2-field':['此字段为必填。']}

*As mentioned on the comments - Don't use dict since it's preserved word on python. *如评论中所述-不要使用dict因为它是python上的保留字。

err = formset.errors
D = {}
for i in len(err):
    crr_field = err[i].keys()[0]
    error_msg  = "{field} error: {error}".format(field=crr_field,error=err[i][crr_field])
    D[i] = error_msg

D will be {1:"Field field1 error: field is required",2:....} D将为{1:"Field field1 error: field is required",2:....}

Try this 尝试这个

results = {}
err = formset.errors
for i, my_dict in enumerate(err):
    for key, value in my_dict.items():
        results[str(i)+'-'+key] = value

items() works in python3, because iteritems() was removed. items()在python3中有效,因为iteritems()已删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM