manChan
manChan

Reputation: 73

How to get value from nested dictionary in python?

I have written a function which will return several dictionaries. For example:

def func()
    return c # <---- nested dictionary

if __name__ == "__main__":
    ans = func()
    print ans             

If I print the ans:

{u'ok': 1.0, u'result': [{u'price': 129.7, u'_id': datetime.datetime(2015, 2, 23, 9, 32)}, {u'price': 129.78, u'_id': datetime.datetime(2015, 2, 23, 9, 33)},
print ans.get('_id')

If I print this, the result is None. How can I get _id?

Upvotes: 0

Views: 594

Answers (4)

smci
smci

Reputation: 33938

func() is actually returning a nested dictionary. Look closely at what your print is telling you. So ans = func() is a nested dictionary:

{u'ok': 1.0, u'result': [{u'price': 129.7, u'_id': datetime.datetime(2015, 2, 23, 9, 32)}, {u'price': 129.78, u'_id': datetime.datetime(2015, 2, 23, 9, 33)},

Hence ans['result'] is itself another dict, or apparently a list containing a dict.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

You could use a list comprehension.

In [19]: ans = {u'ok': 1.0, u'result': [{u'price': 129.7, u'_id': datetime.datetime(2015, 2, 23, 9, 32)}, {u'price': 129.78, u'_id': datetime.datetime(2015, 2, 23, 9, 33)}]}
In [24]: [i['_id'] for i in ans['result']]
Out[24]: [datetime.datetime(2015, 2, 23, 9, 32), datetime.datetime(2015, 2, 23, 9, 33)]
In [25]: [i.get('_id') for i in ans['result']]
Out[25]: [datetime.datetime(2015, 2, 23, 9, 32), datetime.datetime(2015, 2, 23, 9, 33)]

Upvotes: 2

Vivian De Smedt
Vivian De Smedt

Reputation: 1029

From looking at your trace it seems that c is a dictionary containing various other dictionary.

print ans["result"][0]["_id"]

Should return the value you want.

Upvotes: 0

jatinkumar patel
jatinkumar patel

Reputation: 2990

for i in ans['result']:
    print i['_id']

Upvotes: 0

Related Questions