dictionary - Pythonic way to update nested dictionaries in Python -
i have data this:
featurename,machine,licensehost feature1,host1,lichost1 feature1,host2,lichost1 feature2,host1,lichost2 feature1,host1,lichost1 and on...
i want maintain nested dictionary first level of key feature name, next machine name, license host, , value number of times combination occurs.
something like:
dictionary['feature1']['host1']['lichost1'] = 2 dictionary['feature1']['host2']['lichost1'] = 1 dictionary['feature2']['host1']['lichost2'] = 1 the obvious way of creating/updating such dictionary (assuming reading data line line 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 this ensures never run key not found errors @ level.
what best way above (for number of nested levels) ?
you use defaultdict:
from collections import defaultdict import csv def d1(): return defaultdict(int) def d2(): return defaultdict(d1) def d3(): return defaultdict(d2) dictionary = d3() open('input.csv') input_file: next (input_file); 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 if multiple function defs bother you, can same thing more succinctly:
dictionary = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
Comments
Post a Comment