简体   繁体   English

如何从python的嵌套字典中获取价值?

[英]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: 如果我打印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 ? 如何获得_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. 从您的踪迹来看,c似乎是一个包含各种其他字典的字典。

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

Should return the value you want. 应该返回您想要的值。

func() is actually returning a nested dictionary . func()实际上返回的是嵌套字典 Look closely at what your print is telling you. 仔细看看您的印刷品告诉您什么。 So ans = func() is a nested dictionary: 所以ans = func()是一个嵌套的字典:

{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. 因此,ans ['result']本身就是另一个字典,或者显然是一个包含字典的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM