I would like to divide 2 dictionary of different structure, I have found my desired result but I feel that my code is too long for this question. Is there a smarter alternative?
I have a dictionary of only d2
d2 = {3: {'good best third': 1, 'mind third': 0, 'bad third': 0}, 2: {'good so second': 0, 'mind second': 1, 'bad second': 2}, 1: {'good': 2, 'mind': 0, 'bad': 1}}
and then want to divide by the sum of all values in responding of the parent key. For simple explanation, which I have written it as below:
d1 = {3: 1, 2: 3, 1: 3}
The goal is to calculate d3, where
dict3 = d2 / d1
My code
import copy
temp = []
all_vote_len_dict = {3: {'good best third': 1, 'mind third': 0, 'bad third': 0}, 2: {'good so second': 0, 'mind second': 1, 'bad second': 2}, 1: {'good': 2, 'mind': 0, 'bad': 1}}
d1 = copy.deepcopy(all_vote_len_dict)
d2 = copy.deepcopy(all_vote_len_dict)
# to know total number of vote received per unique post
for key, values in d1.items():
temp.append(sum(values.values()))
temp.append(sum(values.values()))
temp.append(sum(values.values()))
counter=0
for keys, values in d1.items():
for key, value in values.items():
values[key]=temp[counter]
counter =1
dict3={}
for (k,dict1), (k2,dict2) in zip(d1.items(), d2.items()):
dict3[k]=({k: (dict2[k] / dict1[k]) for k in dict1})
dict3
Result of dict3
{3: {'good best third': 1.0, 'mind third': 0.0, 'bad third': 0.0},
2: {'good so second': 0.0,
'mind second': 0.3333333333333333,
'bad second': 0.6666666666666666},
1: {'good': 0.6666666666666666, 'mind': 0.0, 'bad': 0.3333333333333333}}
Is there a smarter alternative?
CodePudding user response:
The code below does the "trick"
d2 = {3: {'good best third': 1, 'mind third': 0, 'bad third': 0},
2: {'good so second': 0, 'mind second': 1, 'bad second': 2}, 1: {'good': 2, 'mind': 0, 'bad': 1}}
d1 = {k: sum(vv for vv in v.values()) for k, v in d2.items()}
# d1 is {3: 1, 2: 3, 1: 3}
d3 = {k: {kk: vv / d1[k] for kk, vv in v.items()} for k, v in d2.items()}
for k, v in d3.items():
print(f'{k} -> {v}')
output
3 -> {'good best third': 1.0, 'mind third': 0.0, 'bad third': 0.0}
2 -> {'good so second': 0.0, 'mind second': 0.3333333333333333, 'bad second': 0.6666666666666666}
1 -> {'good': 0.6666666666666666, 'mind': 0.0, 'bad': 0.3333333333333333}