根据其值的类型处理字典,并使用字典理解生成另一个字典
Process a dictionary based on types of it's value and generate another dictionary by using dictionary comprehension
输入字典
{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]}
我正在尝试用字典理解替换上面的代码,我花了几个小时后还是做不到,如果有任何帮助,我们将不胜感激。提前致谢...
你不能用字典理解来做到这一点(只有一个),而是作为一种更 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]})
>>>
使用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]}
输入字典
{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]}
我正在尝试用字典理解替换上面的代码,我花了几个小时后还是做不到,如果有任何帮助,我们将不胜感激。提前致谢...
你不能用字典理解来做到这一点(只有一个),而是作为一种更 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]})
>>>
使用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]}