例如,假設我想建立一個直方圖,我會去這樣的:python可以通過單個命令更新或初始化字典密鑰嗎?
hist = {}
for entry in data:
if entry["location"] in hist:
hist[entry["location"]] += 1
else:
hist[entry["location"]] = 1
有沒有辦法避免的存在檢查和初始化或更新取決於其存在的關鍵?
例如,假設我想建立一個直方圖,我會去這樣的:python可以通過單個命令更新或初始化字典密鑰嗎?
hist = {}
for entry in data:
if entry["location"] in hist:
hist[entry["location"]] += 1
else:
hist[entry["location"]] = 1
有沒有辦法避免的存在檢查和初始化或更新取決於其存在的關鍵?
你想要的這裏是defaultdict
:
from collections import defaultdict
hist = defaultdict(int)
for entry in data:
hist[entry["location"]] += 1
defaultdict
默認構造一個不存在的字典,所以他們整數0開始時,你只需要添加一個爲每中的任何條目項目。
是的,你可以這樣做:
hist[entry["location"]] = hist.get(entry["location"], 0) + 1
對於引用類型,你可以經常使用setdefault
用於此目的,但是當你的dict
的右手邊就是一個整數,這是不恰當的。
Update(hist.setdefault(entry["location"], MakeNewEntry()))
三元運算符是一個命令嗎?
hist[entry["location"]] = hist[entry["location"]]+1 if entry["location"] in hist else 1
(編輯,因爲我搞砸了第一次)
我知道你已經接受一個答案,但只是讓你知道,因爲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
我甚至不知道存在的,但它幾乎是專門爲這個(比defaultdict(INT)更是如此,雖然兩人似乎非常相似)。尼斯。 – Peter
是的,這很方便,儘管我已經學會了2.7版依賴性現在限制其在最終用戶應用中的部署的難題。 – 2011-09-02 10:45:16
哇,非常好。 – tunnuz