Python dictionary for duplicate list

How to convert dictionary to duplicate list in python?

For example: {'a':1,'b':2,'c':1,'d':3} to ['a','b','b','c','d','d','d']

+4
source share
4 answers

Counter.elements from the collections module does just that:

 d = {'a':1,'b':2,'c':1,'d':3} from collections import Counter print sorted(Counter(d).elements()) # ['a', 'b', 'b', 'c', 'd', 'd', 'd'] 
+5
source

You can do this as an understanding of a nested list:

 d = {'a':1,'b':2,'c':1,'d':3} d2 = [k for k, v in d.items() for _ in range(v)] # ['a', 'c', 'b', 'b', 'd', 'd', 'd'] 

However, note that the order will be arbitrary (since the dictionary keys have no order). If you want it to be in alphabetical order, do

 d2 = [k for k, v in sorted(d.items()) for _ in range(v)] # ['a', 'b', 'b', 'c', 'd', 'd', 'd'] 
+4
source
 d = {'a':1,'b':2,'c':1,'d':3} result = [x for k, v in d.items() for x in k * v] 

Or, if you want to ensure an ordered order:

 d = {'a':1,'b':2,'c':1,'d':3} result = [x for k in sorted(d) for x in k * d[k]] 
0
source

Using itertools.repeat faster. If D={'a':1,'b':2,'c':1,'d':3}, result=['a','b','b','c','d','d','d'] .

 from itertools import repeat result=reduce(lambda la,lb:la+lb,[list(itertools.repeat(k,v)) for k,v in D.items()],[]) 

A completely understandable way

 from itertools import repeat result=[] for k,v in D.items(): result+=list(repeat(k,v)) 

ps.

假设 你 用 的 OrderedDict. 稍微 解释 一下 第 一种 .reduce 有 三个 参数, 目标 是 把 你 字典 产生 的 list, 通过 最后 一个 初始 值 [], 来 不断 decrease 为 一个 结果 list ". 你 字典 产生 的 list" 就是 通过 items ()生成 的 (key, meaning) 这种 pair 的 list.

0
source

Source: https://habr.com/ru/post/1483892/


All Articles