首页 > 解决方案 > Python从字典内的列表中获取值

问题描述

我有一本看起来像这样的字典:

{
    'Video Content Started': [
        {
            'event_video_properties': ['first', 'first']
        },{
            'event_page_level_properties': ['second', 'second']
        }
    ],
    'Video Content Playing': [
        {
            'event_video_properties': ['third', 'third']
        },{
            'event_page_level_properties': ['fourth', 'fourth']
        }
    ]
}

我想获取所有值的列表(第一、第二、第三、第四)。

标签: pythonpython-3.x

解决方案


给你写了一个 lil 函数,根据你的规范定制......

选项1

struct = {
    'Video Content Started': [
        {
            'event_video_properties': ['first', 'first']
        },{
            'event_page_level_properties': ['second', 'second']
        }
    ],
    'Video Content Playing': [
        {
            'event_video_properties': ['third', 'third']
        },{
            'event_page_level_properties': ['fourth', 'fourth']
        }
    ]
}

def getValues(struct):
    values = []
    for a in struct.keys():
        for b in struct[a]:
            for c in b:
                for d in range(0, len(b[c])):
                    values.append((b[c][d]))
    return values

print(getValues(struct))

以上产生以上...

在此处输入图像描述

选项 2

struct = {
    'Video Content Started': [
        {
            'event_video_properties': ['first', 'first']
        },{
            'event_page_level_properties': ['second', 'second']
        }
    ],
    'Video Content Playing': [
        {
            'event_video_properties': ['third', 'third']
        },{
            'event_page_level_properties': ['fourth', 'fourth']
        }
    ]
}

def getValues(struct):
    values = []
    for a in struct.keys():
        for b in struct[a]:
            for c in b:
                for d in range(0, len(b[c])):
                    if d == 1:  
                        values.append((b[c][d]))
    return values

print(getValues(struct))

上面产生了这个:

在此处输入图像描述


推荐阅读