简体   繁体   English

Python在列表中获取嵌套的字典值

[英]Python get nested dictionary value inside of list

How do I get the start and end values in a dictionary named my_dict with this format: 如何使用以下格式在名为my_dict的字典中获取开始和结束值:

import pprint
pprint.pprint(my_dict)

{'metadata': [{'filename': 'this_is_a_filename',
                  'filepath': 'this_is_a_filepath',
                  'location': 'this_is_a_location',
                  'time': {'end': 1489787859.905748,
                           'start': 1489787843.980593},
                  'place':
                  etc...

Where: my_dict is a dictionary metadata is a dictionary in my_dict time is a dictionary in a list whose index can change 其中: my_dict是一本字典metadata是在一本字典my_dict time是在列表的字典,其索引可以改变

I've tried: 我试过了:

for key in my_dict['metadata'][0]:
    if key == "time":
        print key("end")

but key is a string not an object so key("end") does not work. 但是key是不是对象的字符串,因此key(“ end”)不起作用。 I've searched everything and tried for hours but cannot figure this out. 我已经搜索了所有内容并尝试了几个小时,但无法弄清楚。

EDIT: 编辑:

The user Dan answered correctly below within less than 3 minutes of asking the question :) Dan用户在提出问题的不到3分钟内,在下面正确回答了问题:)

for d in my_dict.get('metadata', []):
    t = d.get('time', {})
    print t.get('end')
    print t.get('start')
for d in my_dict.get('metadata', []):
    t = d.get('time', {})
    print t.get('end')
    print t.get('start')

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

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