将包含项目和计数的字典转换为项目列表

vva*_*zza -1 python arrays dictionary list

我正在尝试将包含项目和计数的python字典转换为项目列表

items = {"hello":2,"world":1}

["hello","hello","world"]

请帮助我如何处理这种逻辑

Dan*_*ejo 7

使用collections.Counter

from collections import Counter

items = {"hello": 2, "world": 1}
result = list(Counter(items).elements())
print(result)
Run Code Online (Sandbox Code Playgroud)

输出量

['hello', 'hello', 'world']
Run Code Online (Sandbox Code Playgroud)

列表理解

result = [key for key, value in items.items() for _ in range(value)]
Run Code Online (Sandbox Code Playgroud)