将多个值附加到字典键
对于 Python 初学者来说,使用字典可能具有挑战性,尤其是在处理多个值时与单个键关联的值。
假设您有一个包含相应值的年份列表,并且想要使用年份作为键创建一个字典。但是,如果一年出现多次,您需要一种机制来附加该年的值。
考虑以下输入数据:
2010 2 2009 4 1989 8 2009 7
您的目标是构建一个字典如下所示:
{ 2010: 2, 2009: [4, 7], # Appended value for the same key 1989: 8 }
要实现此目的,请按照以下步骤操作:
<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>
此代码将创建一个字典,其中年份为键,关联值存储在列表中。如果一年出现多次,其值将附加到列表中。
以上是如何在 Python 中将多个值附加到字典键?的详细内容。更多信息请关注PHP中文网其他相关文章!