【问题标题】:How to loop through two dictionaries in Python如何在 Python 中遍历两个字典
【发布时间】:2015-03-28 00:53:32
【问题描述】:

我想创建一个 for 循环,它可以遍历两个字典,进行计算并打印结果。这是代码:

price = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
    }

inventory = {
    "banana": 6,
     "apple": 0,
     "orange": 32,
     "pear": 15
    }

for k, v in price, inventory:
    total = total + price*inventory
    print total

我想知道如果我卖掉这家“商店”里的每件商品,我能赚多少钱。我已经检查了here,但对我来说没有用。

错误信息是这样的:

Traceback (most recent call last):
  File "python", line 15, in <module>
ValueError: too many values to unpack

第 15 行是 for 循环开始的地方。 我不知道我是否在考虑如何以正确的方式做到这一点。

【问题讨论】:

  • 嘿,你使用的是 python 2 还是 python 3?
  • 我正在使用 Python 2,但如果我能回答这两个版本,那就太好了

标签: python loops for-loop dictionary


【解决方案1】:

我认为最简单的解决方案是:

total= 0

for key in prices:
  total += prices[key]*stock[key]

print total 

【讨论】:

    【解决方案2】:

    很抱歉回复晚了,但我想我可以帮助其他偶然发现这个问题的人。

    这看起来像是 Codecademy 的课程之一。

    由于两个字典具有相同的键,因此您可以遍历两个字典以获得如下所示的总数。

    total = 0
    for fruit in price:
        total = total + (price[fruit] * inventory[fruit])
    return total
    

    【讨论】:

      【解决方案3】:

      你可以压缩字典:

      for k, k2 in zip(price,inventory):
          print(price[k]*inventory[k2])
      

      即使您的代码有效,您也将访问键而不是值,因此您需要使用上述每个键来访问 dict 值。

      如果你使用python2,你可以使用itertools.izip:

      from itertools import izip
      for k, k2 in izip(price,inventory):
          print(price[k],inventory[k2])
      

      因为字典是无序的,您需要使用orderedDict 来确保键匹配。

      如果两个字典都具有相同的键,则更简单的解决方案是使用一个字典中的键从两个字典中获取值。

      for k in price:
          print(price[k]*inventory[k])
      

      可以写成:

      total = sum(price[k]*inventory[k]for k in price)
      

      如果您控制如何创建字典,将两者合并到一个字典中,使用价格和库存作为键来存储字典的字典,这将是一个更好的整体解决方案。

      shop_items = {'orange': {'price': 1.5, 'inventory': 32}, 'pear': {'price': 3, 'inventory': 15}, 'banana': {'price': 4, 'inventory': 6}, 'apple': {'price': 2, 'inventory': 0}}
      

      然后得到总数:

      print(sum(d["price"] * d["inventory"] for d in shop_items.itervalues()))
      

      或打印所有可用的项目:

      for k, val in shop_items.iteritems():
          pri,inv = val["price"],val["inventory"]
          print("We have {} {}'s available at a price of ${} per unit".format(inv,k,pri))
      
      We have 32 orange's available at a price of $1.5 per unit
      We have 15 pear's available at a price of $3 per unit
      We have 6 banana's available at a price of $4 per unit
      We have 0 apple's available at a price of $2 per unit
      

      如果您正在处理金钱问题,您应该真正使用decimal 库。

      【讨论】:

      • 这不是对无序集合的顺序做出了相当大的假设吗? IE。 k == k2?
      • @aruisdante,这是 OP 试图做的事情,我将使用 OrderedDict 添加一个示例
      • 当然,但是如果字典总是具有相同的键集,那么简单地制作一个字典items = { 'name' : (price, quantity) } 会更有效。我认为对两本词典的期望是允许比库存中的项目更高的价格,但也许不是。
      • @aruisdante,我想这完全取决于创建原始字典的位置和最简单的解决方案就是从一个字典中获取密钥
      【解决方案4】:

      如果我们假设inventory 中的键始终是price 中的键的子集(或者如果不是,则至少这是一个错误条件),那么您只需执行以下操作:

      total = 0
      for item, quantity in inventory.iteritems(): #just use .items() in python 3
          try:
              item_price = price[item]
              total     += item_price*quantity
          except KeyError as e:
              print('Tried to price invalid item' + str(e))
              raise
      print('Total value of goods: $' + str(total))
      

      如果我们不关心错误情况,这可以转换为简单的单行:

      total = sum(price[item]*quantity for item, quantity in inventory.iteritems())
      

      【讨论】:

        【解决方案5】:

        您可以使用dict.items 获取两个字典的项目然后zip 项目并添加相应的价格:

        >>> map(lambda x:x[0][1]+x[1][1], zip(price.items(), inventory.items())
        ... )
        [33.5, 18, 10, 2]
        

        您还可以将其保存在带有字典理解的单独字典中:

        >>> s={k[0]:k[1]+v[1] for k,v in zip(price.items(), inventory.items())}
        >>> s
        {'orange': 33.5, 'pear': 18, 'banana': 10, 'apple': 2}
        

        【讨论】:

          【解决方案6】:
          total = 0
          for i in range(len(price.keys())):
              total += price[price.keys()[i]] * inventory[price.keys()[i]]
          print total
          

          【讨论】:

            猜你喜欢
            • 2018-01-01
            • 1970-01-01
            • 2013-06-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-03-22
            • 2020-10-30
            • 2021-08-07
            相关资源
            最近更新 更多