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

Linda Hamilton
Release: 2024-10-28 11:12:01
Original
296 people have browsed it

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>
Copy after login

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

2010
2
2009
4
1989
8
2009
7
Copy after login

would produce the following dictionary:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!