Python中更新嵌套字典的Python方法

2024-04-25 12:51:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些这样的数据:

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

这确保我在任何级别都不会遇到“找不到键”错误。在

上面的任何一个嵌套的方法是什么?在


Tags: 数据方法indictionaryif字典licenseline
1条回答
网友
1楼 · 发布于 2024-04-25 12:51:28

您可以使用defaultdict

from collections import defaultdict
import csv

def d1(): return defaultdict(int)
def d2(): return defaultdict(d1)
def d3(): return defaultdict(d2)
dictionary = d3()

with open('input.csv') as input_file:
    next (input_file);
    for line in csv.reader(input_file):
        dictionary[line[0]][line[1]][line[2]] += 1

assert dictionary['Feature1']['host1']['lichost1'] == 2
assert dictionary['Feature1']['host2']['lichost1'] == 1
assert dictionary['Feature2']['host1']['lichost2'] == 1
assert dictionary['InvalidFeature']['host1']['lichost1'] == 0

如果多重函数def困扰你,你可以更简洁地说同样的话:

^{pr2}$

相关问题 更多 >