3

Input dictionary

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

I need to form another dictionary based on types of items in input dictionary, it would be like :-

{type: list of keys which has this type}

Expected output would be

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

I have written below code for this:-

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]}

I am trying to replace above code with dictionary comprehension, I couldn't do it after spending hours, Any help would be appreciated. Thanks in advance...

Craig Burgler
  • 1,749
  • 10
  • 19
AlokThakur
  • 3,599
  • 1
  • 19
  • 32

2 Answers2

1

You can't do this with dictionary comprehension (only with one), instead as a more pythonic way you can use 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]})
>>> 
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

Using defaultdict and dictionary comprehension (kind of):

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)

Output

{<type 'list'>: [1, 3], <type 'int'>: [4, 5], <type 'str'>: [2]}
Craig Burgler
  • 1,749
  • 10
  • 19