Reputation: 2145
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:
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 :).
Upvotes: 0
Views: 1160
Reputation: 29093
OR using collections module:
d = {'a_1_alpha':4, 'a_1_beta' :1, 'a_2_alpha' :2, 'a_2_beta': 3, 'b_1_alpha':2}
from collections import defaultdict
new_d = defaultdict(int)
for k,v in ((tuple(k.split('_')[1:]),v) for k,v in d.iteritems()):
new_d[k] += v
Upvotes: 2
Reputation: 11690
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 using split()
. Here's the code:
new_d = {}
for k, v in d.items():
u, n, r = k.split('_')
new_d[(n, r)] = v + new_d.get((n, r), 0)
Upvotes: 6
Reputation: 7613
This should solve your problem:
new_d = {}
for n in nums:
for r in ratios:
for k, v in d.items():
if r in k and n in k:
try:
old = new_d[(n, r)]
except:
old = 0
new_d[(n, r)] = v + old
for p, q in new_d.items():
print (p, q)
Btw. you also forgot to check that n in k
when determining whether the key is viable.
Upvotes: 2