簡體   English   中英

檢查字典中是否已存在鍵的“ pythonic”策略

[英]A “pythonic” strategy to check whether a key already exists in a dictionary

我經常處理異構數據集,並在python例程中將它們作為字典獲取。 我通常會遇到這樣一個問題,即將添加到字典中的下一個條目的鍵已經存在。 我想知道是否存在更“ pythonic”的方式來執行以下任務:檢查密鑰是否存在,並創建/更新我字典的相應對密鑰項

myDict = dict()
for line in myDatasetFile:
   if int(line[-1]) in myDict.keys():
        myDict[int(line[-1])].append([line[2],float(line[3])])
   else:
        myDict[int(line[-1])] = [[line[2],float(line[3])]]

使用defaultdict

from collections import defaultdict

d = defaultdict(list)

# Every time you try to access the value of a key that isn't in the dict yet,
# d will call list with no arguments (producing an empty list),
# store the result as the new value, and give you that.

for line in myDatasetFile:
    d[int(line[-1])].append([line[2],float(line[3])])

另外, 切勿 thing in d.keys()使用thing in d.keys() 在Python 2中,這將創建一個鍵列表,並一次遍歷其中一項來查找鍵,而不是使用基於哈希的查找。 在Python 3中,它並沒有那么可怕,但是它仍然是多余的,並且仍然比正確的方法慢,這是thing in d

它是dict.setdefault的用途。

setdefault(key[, default])

如果key在字典中,則返回其值。 如果不是,請插入具有默認值的密鑰,然后返回默認值。 默認默認為無。

例如:

>>> d={}
>>> d.setdefault('a',[]).append([1,2])
>>> d
{'a': [[1, 2]]}

Python遵循這樣的想法:請求寬容比允許容易。

所以真正的Python方式是:

try:
    myDict[int(line[-1])].append([line[2],float(line[3])])
except KeyError:
    myDict[int(line[-1])] = [[line[2],float(line[3])]]

以供參考:

https://docs.python.org/2/glossary.html#term-eafp

https://stackoverflow.com/questions/6092992/why-is-it-easier-to-ask-forgiveness-than-permission-in-python-but-not-in-java

遇到KeyError時嘗試捕獲Exception

myDict = dict()
for line in myDatasetFile:
   try:
        myDict[int(line[-1])].append([line[2],float(line[3])])
   except KeyError:
        myDict[int(line[-1])] = [[line[2],float(line[3])]]

或使用:

myDict = dict()
for line in myDatasetFile:
   myDict.setdefault(int(line[-1]),[]).append([line[2],float(line[3])])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM