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

Time:10-11

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

CodePudding user response:

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()
  • Related