用于检查密钥是否已存在于字典中的"pythonic"策略

Sir*_*irC 0 python dictionary key

我经常处理异构数据集,并在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])]]
Run Code Online (Sandbox Code Playgroud)

use*_*ica 7

用一个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])])
Run Code Online (Sandbox Code Playgroud)

另外,永远不要使用thing in d.keys().在Python 2中,这将创建一个键列表,并一次迭代一个项以查找键而不是使用基于散列的查找.在Python 3中,它并不是那么可怕,但它仍然是多余的,并且仍然比正确的方式慢,这是thing in d.