我有一些这样的数据:
FeatureName,Machine,LicenseHost
Feature1,host1,lichost1
Feature1,host2,lichost1
Feature2,host1,lichost2
Feature1,host1,lichost1
等等。。。在
我想维护一个嵌套字典,其中第一级键是特性名,下一级是机器名,最后是许可证主机名,值是组合发生的次数。在
比如:
^{pr2}$创建/更新这样一个字典的明显方法是(假设我正在从CSV逐行读取数据):
for line in file:
feature, machine, license = line.split(',')
if feature not in dictionary:
dictionary[feature] = {}
if machine not in dictionary[feature]:
dictionary[feature][machine] = {}
if license not in dictionary[feature][machine]:
dictionary[feature][machine][license] = 1
else:
dictionary[feature][machine][license] += 1
这确保我在任何级别都不会遇到“找不到键”错误。在
上面的任何一个嵌套的方法是什么?在
您可以使用
defaultdict
:如果多重函数
^{pr2}$def
困扰你,你可以更简洁地说同样的话:相关问题 更多 >
编程相关推荐