GoobyPrs
GoobyPrs

Reputation: 615

Python cant make dictionary from list of dictionaries

I have list of dictionaries as a result of django formset error:

[{}, {"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. How can I solve that? Thanks

Upvotes: 1

Views: 108

Answers (3)

doru
doru

Reputation: 9110

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.

Upvotes: 0

Or Duan
Or Duan

Reputation: 13840

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.:

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.']}

*As mentioned on the comments - Don't use dict since it's preserved word on python.

Upvotes: 2

Aviah Laor
Aviah Laor

Reputation: 3658

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:....}

Upvotes: 0

Related Questions