【发布时间】: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