【问题标题】:Process a dictionary based on types of it's value and generate another dictionary by using dictionary comprehension根据其值的类型处理字典并使用字典理解生成另一个字典
【发布时间】:2017-01-04 05:06:33
【问题描述】:

输入字典

{11: [1, 2], 23: 'ewewe', 3: [4], 41: 5, 55: 6}

我需要根据输入字典中的项目类型形成另一个字典, 就像:-

{type: list of keys which has this type}

预期的输出是

{<type 'list'>: [11, 3], <type 'str'>: [23], <type 'int'>: [41, 55]}

我为此编写了以下代码:-

input_dict = {1: [1, 2], 2: 'ewewe', 3: [4], 4: 5, 5: 6}
>>> d = {}
>>> seen = []
for key,val in input_dict.items():
    if type(val) in seen:
        d[type(val)].append(key)
    else:
        seen.append(type(val))
        d[type(val)] = [key]
>>> d
{<type 'list'>: [1, 3], <type 'str'>: [2], <type 'int'>: [4, 5]}

我正在尝试用字典理解替换上面的代码,花了几个小时后我无法做到,任何帮助将不胜感激。提前谢谢...

【问题讨论】:

    标签: python dictionary dictionary-comprehension


    【解决方案1】:

    你不能用字典理解来做到这一点(只有一个),而是作为一种更pythonic的方式你可以使用collections.defaultdict()

    >>> from collections import defaultdict
    >>> d = defaultdict(list)
    >>> 
    >>> test = {11: [1, 2], 23: 'ewewe', 3: [4], 41: 5, 55: 6}
    >>> 
    >>> for i, j in test.items():
    ...     d[type(j)].append(i)
    ... 
    >>> d
    defaultdict(<type 'list'>, {<type 'list'>: [3, 11], <type 'str'>: [23], <type 'int'>: [41, 55]})
    >>> 
    

    【讨论】:

      【解决方案2】:

      使用defaultdict 和字典理解(有点):

      from collections import defaultdict
      
      input_dict = {1: [1, 2], 2: 'ewewe', 3: [4], 4: 5, 5: 6}
      
      d = defaultdict(list)
      {d[type(value)].append(key) for key, value in input_dict.items()}
      d = dict(d)
      
      print(d)
      

      输出

      {<type 'list'>: [1, 3], <type 'int'>: [4, 5], <type 'str'>: [2]}
      

      【讨论】:

        猜你喜欢
        • 2023-01-20
        • 1970-01-01
        • 2013-02-13
        • 2016-10-01
        • 1970-01-01
        • 2021-07-24
        • 1970-01-01
        • 2018-06-21
        • 1970-01-01
        相关资源
        最近更新 更多