如何循环遍历 Python 中的两个词典

How to loop through two dictionaries in Python

我想做一个可以遍历两个字典的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

我想知道如果我把这个"store"里的所有东西都卖了能赚多少钱。我已经检查过 here,但对我来说没有用。

错误信息是这样的:

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

第 15 行是 for 循环开始的地方。 不知道我是不是在思考如何以正确的方式去做。

你可以压缩字典:

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

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

如果您使用 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 .5 per unit
We have 15 pear's available at a price of  per unit
We have 6 banana's available at a price of  per unit
We have 0 apple's available at a price of  per unit

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

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

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

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

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

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

由于两个词典具有相同的键,您可以循环遍历两个词典以获得总计,如下所示。

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

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

total= 0

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

print total