2011-09-02 23 views

回答

15

你想要的這裏是defaultdict

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

defaultdict默認構造一個不存在的字典,所以他們整數0開始時,你只需要添加一個爲每中的任何條目項目。

10

是的,你可以這樣做:

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

對於引用類型,你可以經常使用setdefault用於此目的,但是當你的dict的右手邊就是一個整數,這是不恰當的。

Update(hist.setdefault(entry["location"], MakeNewEntry())) 
0

三元運算符是一個命令嗎?

hist[entry["location"]] = hist[entry["location"]]+1 if entry["location"] in hist else 1 

(編輯,因爲我搞砸了第一次)

5

我知道你已經接受一個答案,但只是讓你知道,因爲Python 2.7,另外還有Counter模塊,這是明確爲這種情況而製造。

from collections import Counter 

hist = Counter() 
for entry in data: 
    hist[entry['location']] += 1 

http://docs.python.org/library/collections.html#collections.Counter

+0

我甚至不知道存在的,但它幾乎是專門爲這個(比defaultdict(INT)更是如此,雖然兩人似乎非常相似)。尼斯。 – Peter

+0

是的,這很方便,儘管我已經學會了2.7版依賴性現在限制其在最終用戶應用中的部署的難題。 – 2011-09-02 10:45:16

+0

哇,非常好。 – tunnuz