python - 如果键,值对存在于字典中跳过python

标签 python dictionary

我有两个变量想要使用collections.defaultdict(list)添加到字典中 这是两个变量:

score = [0, 5, 7, 7, 8, 7]
match = ['turtle', 'cat', 'horse', 'horse', 'dog', 'bear']

我想做的是删除字典中已有的键/值对。现在我正在使用这种方法创建我的字典:

  scoring = collections.defaultdict(list)
  scoring[score].append(match)

但是,这个方法给了我一个像这样的字典:

dictionary = {0: ['turtle'], 5: ['cat'], 7: ['horse', 'horse', 'bear'], 8: ['dog']}

但是,我只希望马在字典中出现一次。是否有办法防止以这种方式在字典中添加相同的键/值对?

最佳答案

您可以使用 set() 而不是 list 来保留值:

>>> coring = defaultdict(set)
>>> for i,j in zip(score, match):
...     coring[i].add(j)
... 
>>> coring
defaultdict(<type 'set'>, {0: set(['turtle']), 8: set(['dog']), 5: set(['cat']), 7: set(['horse', 'bear'])})
>>> 

由于 set 对象不保留顺序,如果您关心值的项目顺序,可以使用 OrdereDict 作为值容器:

>>> from collections import defaultdict, OrderedDict
>>> coring = defaultdict(OrderedDict)
>>> 
>>> for i,j in zip(score, match):
...     coring[i][j]=None
... 
>>> coring
defaultdict(<class 'collections.OrderedDict'>, {0: OrderedDict([('turtle', None)]), 8: OrderedDict([('dog', None)]), 5: OrderedDict([('cat', None)]), 7: OrderedDict([('horse', None), ('bear', None)])})
>>> 
>>> coring[7]
OrderedDict([('horse', None), ('bear', None)])
>>> coring[7].keys()
['horse', 'bear']

关于python - 如果键,值对存在于字典中跳过python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800256/

相关文章:

python 字符串列表转换为字典列表

python - openstack ceiolometer 在安装时抛出未知错误

python - environment.yml中的pip包如何使用.condarc中提供的代理?

dictionary - 在 Swift 中,我可以使用元组作为字典中的键吗?

python - “property”对象不可迭代,尝试在调用正在使用的 API 后获取响应

python - 无法更新词典

python - 在不明确调用键名的情况下解析 json

python - 文本聚类/NLP

python - 过滤掉重复的表条目

python - defaultdict 带有类构造函数的参数