如何在 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學習者快速成長!