How to access key values of ordered dict in django serializer query

Question:

I work with Django-Rest api and have serializer that returns me the data like this

my_ordered = [OrderedDict([(‘idx’, ‘1231233’), (‘rock’, None), (‘Email’, ‘[email protected]’)]), OrderedDict([(‘idx’, ‘1212333’), (‘paper’, None), (‘Email’, ‘[email protected]’)])]

type(my_ordered)    
<class 'collections.OrderedDict'>

I tried to access its ‘Email’ key like this

for trainer, training in my_ordered.items():
     print(training['Email'])

NameError: name ‘OrderedDict’ is not defined

Also tried

import collections
my_ordered = [collections.OrderedDict([('idx', '1231233'), ('rock', None), ('Email', '[email protected]')]), collections.OrderedDict([('idx', '1212333'), ('paper', None), ('Email', '[email protected]')])]
#my_ordered.keys()[2]
for trainer, training in my_ordered.items():
     print(training['Email'])

my_ordered.keys()[2]

AttributeError: ‘list’ object has no attribute ‘items’

but this also not helped.

How to access key values in ordered dictionary

Asked By: Alexander

||

Answers:

Look here:

my_ordered = [collections.OrderedDict(...)]

Your my_ordered is actually a list of OrderedDicts. You can get to one with in example:

my_ordered[0].keys()
Answered By: NixonSparrow
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.