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
Your goal is to construct a dictionary that looks like this:
{ 2010: 2, 2009: [4, 7], # Appended value for the same key 1989: 8 }
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>
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!