If I have a dictionary as follows (with some lists):
units = ['a','b']
nums = ['1','2']
ratios = ['alpha', 'beta']
d = {'a_1_alpha':4, 'a_1_beta' :1, 'a_2_alpha' :2, 'a_2_beta': 3, 'b_1_alpha':2}
How do i from a new dictionary which:
- forms a key comprising of tuple (num,ratio) #items from list nums & ratios
- the value would be the sum of the earlier dictionary (d) value.
i.e.
new_d = { ('1','alpha'): 6, ('1','beta'): 1, ('2','alpha'): 2, ('2','beta'): 3}
I have the following code, but doesn’t seem right.
new_d = {}
for num in nums:
for ratio in ratios:
for k,v in d.items():
if ratio in k:
try:
oldval = dict[num,ratio]
except:
oldval = 0
new_d[(num,ratio)] = oldval + v
for p,q in new_d.items():
print p,q
Please help to comment/advice.
Thanks :).
The two outer loops are redundant, simply iterate over the key-value pairs of
d. You can easily extract the three components of a key usingsplit(). Here’s the code: