0

I'm almost confident there is a more Pythonic way of writing this code. The goal here is to increase a dictionary value by 1 or create the entry if it doesn't exist. My current code is:

#!python3 
DICT = {}
if 'KEY' not in DICT:
  DICT['KEY'] = 1
else:
  DICT['KEY'] += 1

I would have sworn that there was a manner of consolidating this into a single line without the need for if/else.

Thanks!

  • `d.setdefault("key",[]).append("whatever")` for ints have a look at a defaultdict(int). - that is much better then using something like `d["key"] = d.setdefault("key", 0) + 1` – Patrick Artner Oct 02 '21 at 14:34
  • 1
    Does this answer your question? [Using a dictionary to count the items in a list](https://stackoverflow.com/questions/3496518/using-a-dictionary-to-count-the-items-in-a-list) – mkrieger1 Oct 02 '21 at 14:46
  • also a possibility: `DICT['KEY'] = DICT.get("KEY",0) + 1` - but collections.defaultdict(int) is just nicer: [collections.defaultdict](https://docs.python.org/3.8/library/collections.html#collections.defaultdict) – Patrick Artner Oct 02 '21 at 14:49
  • 1
    See also https://stackoverflow.com/questions/19883015/python-collections-counter-vs-defaultdictint – mkrieger1 Oct 02 '21 at 14:56
  • Thanks @PatrickArtner, the DICT.get() function is what I was thinking of. I'll have to take a look at collections.defaultdict. – Charles Consumé Oct 03 '21 at 21:53

0 Answers0