检测python中的重复键

2024-04-18 08:25:03 发布

您现在位置: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 = times + 1 

这将返回1。即使我检查字典的长度,它也会显示3,这意味着只有一个键“a”被计算在内。你知道吗


Tags: 对象方法函数inforif字典items
3条回答

字典不包含重复的键。最后输入的key将由字典存储。你知道吗

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.

我希望这对你有帮助。你知道吗

不能。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']) 

根据定义,字典没有重复的键。阅读docs。尝试添加与现有项具有相同密钥的新项将覆盖旧项。请尝试打印您的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

相关问题 更多 >