list - loop inside a dictionary python -
i starting learning django , python... it's been 2 months. i'm doing 1 of own personal projects , have section querying webservice , passing result templates.
the webservice returning dictionary below.
x = {'id':[{ 'key-1': 'first name', 'key-2': 'john' },{ 'key-1': 'last name', 'key-2': 'doe' },{ 'key-1': 'age', 'key-2': '25' }]
i expecting iterate list inside dictionary , create own dictionary below:
d = {'first name': 'john', 'last name': 'doe', 'age': '25' }
i not sure missing, can please me learning how build dictionary?
caveat aware of ordering rules values
method dictionaries.
ordering rules 2.x documentation , 3.x documentation.
edit2:
to prevent weirdness dictionary ordering , provided solution, wrap data ordereddict:
from collections import ordereddict x = {'id':[ordereddict({ 'key-1': 'first name', 'key-2': 'john' }),ordereddict({ 'key-1': 'last name', 'key-2': 'doe' }),ordereddict({ 'key-1': 'age', 'key-2': '25' })]}
dict()
nice option this:
d = dict(each.values() each in x['id'])
output:
{'age': '25', 'first name': 'john', 'last name': 'doe'}
Comments
Post a Comment