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!