简体   繁体   中英

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 ?

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)]
for i in ans['result']:
    print i['_id']

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.

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.

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