Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible, in python, to update or initialize a dictionary key with a single command?

For instance, say I want to build an histogram, I would go like that:

hist = {}
for entry in data:
    if entry["location"] in hist:
        hist[entry["location"]] += 1
    else:
        hist[entry["location"]] = 1

Is there a way to avoid the existence check and initialize or update the key depending on its existence?

like image 399
tunnuz Avatar asked Sep 02 '11 07:09

tunnuz


2 Answers

What you want here is a defaultdict:

from collections import defaultdict
hist = defaultdict(int)
for entry in data:
    hist[entry["location"]] += 1

defaultdict default-constructs any entry that doesn't already exist in the dict, so for ints they start out at 0 and you just add one for every item.

like image 60
Peter Avatar answered Oct 05 '22 03:10

Peter


Yes, you can do:

hist[entry["location"]] = hist.get(entry["location"], 0) + 1

With reference types, you can often use setdefault for this purpose, but this isn't appropriate when the right hand side of your dict is just an integer.

Update( hist.setdefault( entry["location"], MakeNewEntry() ) )
like image 38
CB Bailey Avatar answered Oct 05 '22 04:10

CB Bailey