简体   繁体   中英

How to create a dictionary from a list where the count of each element is the key and values are the lists of the according element?

For Example:

list = [1,2,2,3,3,3,4,4,4,4]

the output should be:

{1:[1],2:[2,2],3:[3,3,3],4:[4,4,4,4]}

where the key = 1 is the count of the the element 1 and the value is the list containing all the elements whose count is 1 and so on.

The following code creates three dictionaries where the case when the same count occurs multiple times is handled differently:

l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 44, 44, 44, 44]

d_replace = dict()
d_flat = dict()
d_nested = dict()
for item in set(l):
    elements = list(filter(lambda x: x == item, l))
    key = len(elements)
    d_replace[key] = elements
    d_flat.setdefault(key, list()).extend(elements)
    d_nested.setdefault(key, list()).append(elements)

print('Dictionary with replaced elements:\n', d_replace)
print('\nDictionary with a flat list of elements\n', d_flat)
print('\nDictionary with a nested lists of elements\n', d_nested)

Output:

Dictionary with replaced elements:
 {1: [1], 2: [2, 2], 3: [3, 3, 3], 4: [44, 44, 44, 44]}

Dictionary with a flat list of elements
 {1: [1], 2: [2, 2], 3: [3, 3, 3], 4: [4, 4, 4, 4, 44, 44, 44, 44]}

Dictionary with a nested lists of elements
 {1: [[1]], 2: [[2, 2]], 3: [[3, 3, 3]], 4: [[4, 4, 4, 4], [44, 44, 44, 44]]}
  • d_replace : the according list of elements is overwritten.
  • d_flat : contains a single list of elements with the according count
  • d_nested : contains a list of lists of elements with the according count

You can try to use dict comprehension with filter or list comprehension

ls = [1,2,2,3,3,3,4,4,4,4]

print({ls.count(i): [el for el in ls if el == i] for i in set(ls)})

OR

print({ls.count(i): list(filter(lambda x: x == i, ls)) for i in set(ls)})

Output

{1: [1], 2: [2, 2], 3: [3, 3, 3], 4: [4, 4, 4, 4]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM