如果可能有重复键,如何添加到字典?
在Python中,字典是一种无序的键值对集合,其中键是唯一的。如果要在字典中添加重复键,可以使用列表或元组作为值来存储多个值。以下是一些方法来处理重复键的添加:
my_dict = {}
key = "key1"
value1 = "value1"
value2 = "value2"
if key in my_dict:
my_dict[key].append(value1)
else:
my_dict[key] = [value1]
if key in my_dict:
my_dict[key].append(value2)
else:
my_dict[key] = [value2]
my_dict = {}
key = "key1"
value1 = "value1"
value2 = "value2"
if key in my_dict:
my_dict[key] += (value1,)
else:
my_dict[key] = (value1,)
if key in my_dict:
my_dict[key] += (value2,)
else:
my_dict[key] = (value2,)
from collections import defaultdict
my_dict = defaultdict(list)
key = "key1"
value1 = "value1"
value2 = "value2"
my_dict[key].append(value1)
my_dict[key].append(value2)
from collections import Counter
my_dict = {}
key = "key1"
value1 = "value1"
value2 = "value2"
if key in my_dict:
my_dict[key] = Counter(my_dict[key])
my_dict[key][value1] += 1
else:
my_dict[key] = Counter({value1: 1})
if key in my_dict:
my_dict[key][value2] += 1
else:
my_dict[key] = Counter({value2: 1})
这些方法可以帮助您在字典中添加重复键,并根据需要存储多个值。
领取专属 10元无门槛券
手把手带您无忧上云