如何在 Python 中将多个值附加到字典键?

Susan Sarandon
发布: 2024-10-27 15:18:02
原创
263 人浏览过

How to Append Multiple Values to a Dictionary Key in Python?

将多个值附加到字典键

对于 Python 初学者来说,使用字典可能具有挑战性,尤其是在处理多个值时与单个键关联的值。

假设您有一个包含相应值的年份列表,并且想要使用年份作为键创建一个字典。但是,如果一年出现多次,您需要一种机制来附加该年的值。

考虑以下输入数据:

2010
2
2009
4
1989
8
2009
7
登录后复制

您的目标是构建一个字典如下所示:

{
    2010: 2,
    2009: [4, 7],  # Appended value for the same key
    1989: 8
}
登录后复制

要实现此目的,请按照以下步骤操作:

<code class="python">years_dict = {}  # Empty dictionary to store years and values

# Iterate through the list of years and values
for line in list:
    year = line[0]   # Extract the year from the line
    value = line[1]  # Extract the value for the year

    # Check if the year is already in the dictionary
    if year in years_dict:
        # If it is, append the new value to the existing list
        years_dict[year].append(value)
    else:
        # If it's a new year, create a new list and add the first value
        years_dict[year] = [value]</code>
登录后复制

此代码将创建一个字典,其中年份为键,关联值存储在列表中。如果一年出现多次,其值将附加到列表中。

以上是如何在 Python 中将多个值附加到字典键?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!