简体   繁体   中英

loop inside a dictionary python

I am just starting learning Django and Python... It's been 2 months. I'm doing one of my own personal projects and i have a section where i am querying a webservice and passing back the result to the templates.

The webservice is returning a dictionary like below.

x =  {'ID':[{
    'key-1': 'First Name',
    'key-2': 'John'
},{
    'key-1': 'Last Name',
    'key-2': 'Doe'
},{
    'key-1': 'Age',
    'key-2': '25'
}]

I am expecting to iterate the list inside the dictionary and create my own dictionary like the below:

d = {'First Name': 'John', 'Last Name': 'Doe', 'Age': '25' }

I am not sure what am i missing, can someone please help me with learning how to build my dictionary?

Try a dict comprehension and build a new dictionary with key-1 as the key and key-2` as the value.

x = {'ID':[{
    'key-1': 'First Name',
    'key-2': 'John'
},{
    'key-1': 'Last Name',
    'key-2': 'Doe'
},{
    'key-1': 'Age',
    'key-2': '25'
}]}


print({el['key-1']: el['key-2'] for el in x['ID']})

Result

{'Age': '25', 'First Name': 'John', 'Last Name': 'Doe'}

Caveat be aware of ordering rules for values method for dictionaries.

Ordering rules 2.x documentation and 3.x documentation .

EDIT2:

To prevent any weirdness with dictionary ordering and the provided solution, wrap your data into an 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() is a nice option for something like this:

d = dict(each.values() for each in x['ID'])

output:

{'Age': '25', 'First Name': 'John', 'Last Name': 'Doe'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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