convert tuple keys of dict into a new dict

后端 未结 3 1339
暖寄归人
暖寄归人 2021-01-24 01:46

I have a dict like this:

{
    (\'America\', 25, \'m\', \'IT\'): 10000,
    (\'America\', 22, \'m\', \'IT\'): 8999,
    (\'Japan\',   24, \'f\', \'I         


        
3条回答
  •  失恋的感觉
    2021-01-24 02:37

    You can replace your entire try/except with this:

    res.setdefault((country, sex, job), {})[age] = cnt
    

    Or you could make res a defaultdict(dict) and then it becomes:

    res[country, sex, job][age] = cnt
    

提交回复
热议问题