python中从字典列表中提取元素

2024-04-27 05:17:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个字典对象列表:

[{'Id': 46, 'Date': '2016-05-09T00:00:00', 'Type': 1, 'PId': None, 'Ct': None},
{'Id': 108, 'Date': '2017-07-01T00:00:00', 'Type': 10, 'PId': None, 'Ct': None}]

我可以这样做从列表的第一个元素中提取Date

list_dict[0].get('Date')

如何获得Date对应于Type10的Date(没有硬编码,它是列表中的第二个元素)?如果Type10不存在,则解决方案应返回None

--编辑:

问题的前一个版本假设列表是json对象,它们实际上是字典


Tags: 对象noneid元素编码列表getdate
2条回答

简单回路

您可以使用一个简单的循环,将Type设置为10的第一个字典

lst = [
    {'Id': 46, 'Date': '2016-05-09T00:00:00', 'Type': 1, 'PId': None, 'Ct': None},
    {'Id': 108, 'Date': '2017-07-01T00:00:00', 'Type': 10, 'PId': None, 'Ct': None},
]
type_10_date = None
for obj in lst:
    if obj.get('Type') == 10:
        type_10_date = obj.get('Date')

print(type_10_date)
# 2017-07-01T00:00:00

使用过滤器

如果您愿意,还可以使用内置的filter函数,该函数接受一个谓词函数,该函数确定应返回iterable中的哪些值(在本例中为list注意:我为从内置filter函数获得filter对象的python3用户提供了一个到list的转换

type_10_objs = list(filter(lambda d: d.get('Type') == 10, lst))
if type_10_objs:  # This could be an empty list!
    print(type_10_objs[0].get('Date'))
# 2017-07-01T00:00:00

只需检查类型并返回相应的日期,如下所示:

input = [{'Id': 46, 'Date': '2016-05-09T00:00:00', 'Type': 1, 'PId': None, 'Ct': None}, {'Id': 108, 'Date': '2017-07-01T00:00:00', 'Type': 10, 'PId': None, 'Ct': None}]

def example(input):

    for element in input:
        if element['Type'] == 10:
            return element['Date']

    return None

相关问题 更多 >