Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary default value when there is no key [duplicate]

Is there a more elegant way to achieve this: If the key exists, increment its value by one, otherwise create the key and set its value to 1.

histogram = {}
...
if histogram.has_key(n):
    histogram[n] += 1
else: 
    histogram[n] = 1
like image 898
Ross Marsden Avatar asked Oct 23 '25 06:10

Ross Marsden


1 Answers

from collections import Counter
histogram = Counter()
...
histogram[n] += 1

For values other than numbers, check out collections.defaultdict. In this case you could use defaultdict(int) instead of Counter but Counter has added features like .elements() and .most_common(). defaultdict(list) is another very useful example.

Counter also has a convenient constructor. Instead of:

histogram = Counter()
for n in nums:
    histogram[n] += 1

You can just do:

histogram = Counter(nums)

Other options:

histogram.setdefault(n, 0)
histogram[n] += 1

and

histogram[n] = histogram.get(n, 0) + 1

In the case of lists, setdefault can be a bit more useful as it returns the value, i.e.:

dict_of_lists.setdefault(key, []).append(value)

And as a final bonus, going slightly off track now, here is my most common use of defaultdict:

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
like image 52
Alex Hall Avatar answered Oct 24 '25 20:10

Alex Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!