用Python在字典中添加键

时间:2018-06-27 15:46:59

标签: python python-3.x dictionary counter ordereddictionary

我想添加一个数为1的键,并在每次增加时递增它,这是经典操作。这是我的常规代码。

d = OrderedDict()
for i, v in enumerate(s):
   if v not in d:
      d[v] = 1
   else:
      d[v] += 1

如何使用setdefault而不是collections. Counter用1行代码来完成此操作 就像如果这是一个列表,那我本来可以做到的,

d.setdefault(v, []).append()

是否可以使用整数加法来做类似的事情。

3 个答案:

答案 0 :(得分:6)

您可以执行以下操作:

d[v] = d.get(v, 0) + 1

答案 1 :(得分:3)

只需使用订购的计数器即可。如果您愿意导入OrderedDict,我认为没有理由应避免使用Counter

from collections import OrderedDict, Counter

class OrderedCounter(Counter, OrderedDict):
    pass

s = [3, 1, 3, 1, 2, 3, 4]

d = OrderedCounter(s)

print(d)

OrderedCounter({3: 3, 1: 2, 2: 1, 4: 1})

请注意,在Python 3.7+中,由于字典是按插入顺序排列的,因此您只能使用Counter

答案 2 :(得分:0)

如果我们想使用oneliner,并被允许使用itertools

import itertools

s = [1, 2, 3, 4, 5, 6, 7, 12, 4, 7, 3]

d = {key: len(list(items)) for key, items in itertools.groupby(sorted(s))}
相关问题