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

Susan Sarandon
Release: 2024-10-27 15:18:02
Original
263 people have browsed it

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

Appending Multiple Values to a Dictionary Key

For beginners in Python, working with dictionaries can be challenging, especially when it comes to handling multiple values associated with a single key.

Suppose you have a list of years with corresponding values and want to create a dictionary using the years as keys. However, if a year appears multiple times, you need a mechanism to append the values for that year.

Consider the following input data:

2010
2
2009
4
1989
8
2009
7
Copy after login

Your goal is to construct a dictionary that looks like this:

{
    2010: 2,
    2009: [4, 7],  # Appended value for the same key
    1989: 8
}
Copy after login

To achieve this, follow these steps:

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

This code will create a dictionary where the years are keys and the associated values are stored in lists. If a year appears multiple times, its values are appended to a list.

The above is the detailed content of How to Append Multiple Values to a Dictionary Key in Python?. 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!