convert tuple keys of dict into a new dict

后端 未结 3 1341
暖寄归人
暖寄归人 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:15

    You can use a dict comprehension to do this:

    >>> data = {
    ...     ('America', 25, 'm', 'IT'): 10000,
    ...     ('America', 22, 'm', 'IT'): 8999,
    ...     ('Japan',   24, 'f', 'IT'): 9999,
    ...     ('Japan',   23, 'f', 'IT'): 9000
    ... }
    >>> {x: value for (w, x, y, z), value in data.items() if w == "America" and y == "m" and z == "IT"}
    {25: 10000, 22: 8999}
    

提交回复
热议问题