首页 > 解决方案 > Python 字典乘法键 * 值

问题描述

嘿,每个人都试图在 python 字典中乘以键 * 值。

我有以下代码:

dic = {'coca-cola':3, 'fanta':2}
def inventory(data):
  lis = []
  lis = [key * val for key, val in data.items()]
  return lis
inventory(dic)

但是我的输出是

['coca-colacoca-colacoca-cola', 'fantafanta']

我想得到

['coca-cola', 'coca-cola', 'coca-cola', 'fanta', 'fanta']

请帮忙

标签: pythondictionary

解决方案


使用以下代码。

dic = {'coca-cola':3, 'fanta':2}
def inventory(data):
  lis = []

  for key, val in data.items():
      for item in range(0,val):
          lis.append(key)
  return lis

推荐阅读