0

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?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
ppv
  • 33
  • 5
  • 1
    Can you show what you have you tried so far and talk about the specific problems did you ran into? – pvg Sep 14 '17 at 01:08
  • I tried doing exactly what someone explained over here... https://stackoverflow.com/questions/18289678/python-iterating-through-a-dictionary-with-list-values But it's not the same that i am looking at ... – ppv Sep 14 '17 at 01:11
  • If your outer dict was named `x` just do `{el['key-1']: el['key-2'] for el in x['ID']}` – Paul Rooney Sep 14 '17 at 01:12
  • I'm not sure I understand your comment. Take a look at [ask] and [MCVE] and update your question with the details. – pvg Sep 14 '17 at 01:12
  • @PaulRooney That worked!... Thanks a lot, It's a lot clear now! – ppv Sep 14 '17 at 01:20

2 Answers2

1

Try a dict comprehension and build a new dictionary with key-1 as the key andkey-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'}

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
0

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'}
salparadise
  • 5,699
  • 1
  • 26
  • 32