Home  >  Article  >  Backend Development  >  How to Append Multiple Values to a Single Key in a Python Dictionary?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 11:12:01280browse

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

Appending Multiple Values for One Key in a Dictionary

To create a dictionary with years as keys and associated values as lists in Python, one can approach the task as follows:

<code class="python">years_dict = dict()

for line in list:
    if line[0] in years_dict:
        years_dict[line[0]].append(line[1])
    else:
        years_dict[line[0]] = [line[1]]</code>

The given example, where the input years and associated values are:

2010
2
2009
4
1989
8
2009
7

would produce the following dictionary:

{
    "2010": [2],
    "2009": [4, 7],
    "1989": [8]
}

This approach ensures that each year key in the dictionary has an associated list of values, including any duplicates.

The above is the detailed content of How to Append Multiple Values to a Single Key in a Python Dictionary?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn