gpt4 book ai didi

python - 使用默认值从字典列表中提取项目

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:01 29 4
gpt4 key购买 nike

我想在下面的列表中使用列表理解;

movie_dicts = [
{'title':'A Boy and His Dog', 'year':1975, 'rating':6.6},
{'title':'Ran', 'year':1985, 'rating': 8.3},
{'year':2010, 'rating':8.0},
{'title':'Scanners', 'year':1981, 'rating': 6.7}
]

利用我对列表理解和字典的了解,我知道

title_year = [i['title'] for i in movie_dicts]
print title_year

将打印包含电影标题的列表。但是,由于缺少其中一部电影的片名,我收到以下错误

Traceback (most recent call last):
File "./loadjson.py", line 30, in <module>
title_year = [i['title'] for i in movie_dicts]
KeyError: 'title'

有没有办法检查电影标题是否存在,如果不存在,则在其位置放置一个默认值?

最佳答案

使用 dict.get() method返回丢失键的默认值:

title_year = [i.get('title', '<untitled>') for i in movie_dicts]

这将替换字符串 '<untitled>'缺少标题。或者,过滤掉没有 key 的条目(生成更短的列表):

title_year = [i['title'] for i in movie_dicts if 'title' in i]

关于python - 使用默认值从字典列表中提取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35381080/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com