如何在Python中循环遍历两个字典

时间:2015-01-28 22:42:31

标签: python loops for-loop dictionary

我想制作一个可以通过两个词典的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循环开始的那一行。 我不知道我是否正在考虑如何以正确的方式做到这一点。

6 个答案:

答案 0 :(得分: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])

由于dicts 无序,您需要使用orderedDict来确保密钥匹配。

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

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

可以写成:

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

如果您控制如何创建dicts,将两者组合成一个存储使用价格和库存的dicts字典的dict,因为键将是更好的整体解决方案。

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库。

答案 1 :(得分:1)

如果我们假设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())

答案 2 :(得分:0)

total = 0
for i in range(len(price.keys())):
    total += price[price.keys()[i]] * inventory[price.keys()[i]]
print total

答案 3 :(得分:0)

您可以使用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}

答案 4 :(得分:0)

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

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

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

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

答案 5 :(得分:0)

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

total= 0

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

print total