I have a dict
like this:
{
('America', 25, 'm', 'IT'): 10000,
('America', 22, 'm', 'IT'): 8999,
('Japan', 24, 'f', 'IT'): 9999,
('Japan', 23, 'f', 'IT'): 9000
}
Now, I want to get all result with key ('America', 'm', 'IT')
, in this example. In the above, that would be:
{25: 10000, 22: 8999}
My current solution is below:
res = dict()
for key, cnt in stats.items():
country, age, sex, job = key
try:
res[(country, sex, job)][age] = cnt
except KeyError as e:
res[(country, sex, job)] = {}
res[(country, sex, job)][age] = cnt
print res['America', 'm', 'IT']
Do I have better ways to do is? since this code does not seem that simple.
You can use a dict comprehension to do this: