I have a Python list:
list_1 = [1, 2, 3, 11, 22, 33, 111, 222, 3333, 2222, 1111, 333]
I want to return a dictionary whose keys are the length of the items in the list and values are lists having items of same length as key.
sample output is as shown:
Dict_1 = {1 : [1,2,3],2:[11,22,33],3:[111,222,333]...}
CodePudding user response:
You can do this:
from collections import defaultdict
lst = [1, 2, 3, 11, 22, 33, 111, 222, 3333, 2222, 1111, 333]
d = defaultdict(list)
for item in lst:
d[len(str(item))].append(item)
print(d)
CodePudding user response:
It's prob. easier to just use the power of itertools groupby to solve this:
Notes - it's based on the assumption that the input list is orderly, meaning each item are in ordered fashion. Otherwise, it's expected to sort it first. Thanks for the comments/feedback by @S.B
The rest of formatting and putting into the outputs is left as an exercise. ;-) (Can you try it now?)
# L is your input list
from itertools import groupby
dc = dict()
for k, g in groupby(L, key=lambda x: len(str(x))):
print(k, list(g))
Output:
1 [1, 2, 3]
2 [11, 22, 33]
3 [111, 222]
4 [3333, 2222, 1111]
3 [333]
CodePudding user response:
Dict_1 = {}
for i in list_1:
if len(i) not in Dict_1:
Dict_1[len(i)] = [i]
else:
Dict_1[len(i)].append(i)
print(Dict_1)