检测python中的重复密钥
我有一个大学练习,其中包含一个问题,要求编写一个函数,返回python中某个特定键在对象中重复多少次。在研究字典之后,我知道python会自动忽略重复的键,只保留最后一个键。我试着用传统的方式在每个键上循环:检测python中的重复密钥,python,Python,我有一个大学练习,其中包含一个问题,要求编写一个函数,返回python中某个特定键在对象中重复多少次。在研究字典之后,我知道python会自动忽略重复的键,只保留最后一个键。我试着用传统的方式在每个键上循环: dictt = {'a' : 22, 'a' : 33, 'c' : 34, 'd' : 456} lookFor = 'a' times = 0 for k,v in dictt.items(): if k == lookFor: times = time
dictt = {'a' : 22, 'a' : 33, 'c' : 34, 'd' : 456}
lookFor = 'a'
times = 0
for k,v in dictt.items():
if k == lookFor:
times = times + 1
这将返回1。即使我检查字典的长度,它也会显示3,这意味着只计算了一个键“a”。根据定义,字典没有重复的键。读这本书。尝试添加与现有项具有相同密钥的新项将覆盖旧项。尝试打印dict中的项目:
dictt = {'a' : 22, 'a' : 33, 'c' : 34, 'd' : 456}
for x, y in dictt.items():
print(x, y)
输出:
a 33
c 34
d 456
你不能。Python字典不支持重复键,它将被重写 但是,您可以为它创建一个新的数据类型
class Dictlist(dict):
def __setitem__(self, key, value):
try:
self[key]
except KeyError:
super(Dictlist, self).__setitem__(key, [])
self[key].append(value)
示例使用
>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}
使用Dictlist
数据类型回答您的问题
dictt = dictlist.Dictlist()
dictt['a'] = 22
dictt['a'] = 33
dictt['c'] = 34
dictt['d'] = 456
lookFor = 'a'
len(dictt['a'])
字典不包含重复的键。最后输入的
键
将由字典存储
dictt = {'a' : 22, 'a' : 33, 'c' : 34, 'd' : 456}
# This is your dictionary.
# Now print the dictionary to see it.
print(dictt)
输出:-
{'a': 33, 'c': 34, 'd': 456}
# Now this is your dictionary. Now on whatever the operation you will perform, you are perfroming on this dictionary.
我希望这能对您有所帮助。dicts不能包含重复的密钥。第一个
a
被第二个替换。字典是映射,因此它们不能有重复的键,否则它们将不知道您希望从给定的键中得到什么值