Python dictionary default value when there is no key
本问题已经有最佳答案,请猛点这里访问。
是否有更优雅的方法来实现这一点:如果键存在,将其值递增一,否则创建键并将其值设置为1。
1 2 3 4 5 6 | histogram = {} ... if histogram.has_key(n): histogram[n] += 1 else: histogram[n] = 1 |
1 2 3 4 | from collections import Counter histogram = Counter() ... histogram[n] += 1 |
对于数字以外的值,请检查
1 2 3 | histogram = Counter() for n in nums: histogram[n] += 1 |
你只需做:
1 | histogram = Counter(nums) |
其他选项:
1 2 | histogram.setdefault(n, 0) histogram[n] += 1 |
和
1 | histogram[n] = histogram.get(n, 0) + 1 |
在列表的情况下,
1 | dict_of_lists.setdefault(key, []).append(value) |
最后一个好处是,现在有点偏离轨道,这里是我最常用的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def group_by_key_func(iterable, key_func): """ Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements of the iterable and the values are lists of elements all of which correspond to the key. >>> dict(group_by_key_func("a bb ccc d ee fff".split(), len)) # the dict() is just for looks {1: ['a', 'd'], 2: ['bb', 'ee'], 3: ['ccc', 'fff']} >>> dict(group_by_key_func([-1, 0, 1, 3, 6, 8, 9, 2], lambda x: x % 2)) {0: [0, 6, 8, 2], 1: [-1, 1, 3, 9]} """ result = defaultdict(list) for item in iterable: result[key_func(item)].append(item) return result |