慕田峪7331174
Stock = {1: {'Item Name': "Campbell's Cream of Mushroom", 'Description': 'Canned Food', 'Price': 2.30, 'Stock': 32, 'Expiry Date': '27/05/25'}, 2: {'Item Name': "Orecchiette", 'Description': 'Noodles & Pasta', 'Price': 3.45, 'Stock': 23, 'Expiry Date': '27/05/22'}, 3: {'Item Name': "Coca Cola", 'Description': 'Drinks', 'Price': 1.50, 'Stock': 25, 'Expiry Date': '27/05/21'}, 4: {'Item Name': "Dried Cha Soba", 'Description': 'Noodles & Pasta', 'Price': 3.75, 'Stock': 25, 'Expiry Date': '27/05/22'}, 5: {'Item Name': "Chinese Cabbage", 'Description': "Vegetable", 'Price': 1.50, 'Stock': 12, 'Expiry Date': '8/7/2020'} }items = {}for item in Stock.values(): if item['Item Name'] in items.keys(): items[item['Item Name']] += item['Stock'] else: items[item['Item Name']] = item['Stock']print(items)输出 :{“Campbell's Cream of Mushroom”:32,“Orecchiette”:23,“Coca Cola”:25,“Dried Cha Soba”:25,“Chinese Cabbage”:12}
哆啦的时光机
首先list用作变量名不是一个好主意,因为它是 python 中的保留关键字所以我将变量的名称更改list = []为something = [],其次你已经声明x = 0然后在for loop你写for x in list:的变量类型的地方x是转换为字符串,这就是您收到该错误的原因,所以我建议您使用另一个变量名,我已经编辑了您的代码并将其更改something为上面提到的名称,我快速找到了一个替换all 这就是为什么变量名称newlist也已更改为newsomething,并且在解决您的问题中提到的错误后,您的代码需要进一步修改,但由于您没有简要说明代码的用途,现在我无法帮助您。但是对于您当前的问题,下面是我修改过的代码。Stock = {1: {'Item Name': "Campbell's Cream of Mushroom", 'Description': 'Canned Food', 'Price': 2.30, 'Stock': 32, 'Expiry Date': '27/05/25'}, 2: {'Item Name': "Orecchiette", 'Description': 'Noodles & Pasta', 'Price': 3.45, 'Stock': 23, 'Expiry Date': '27/05/22'}, 3: {'Item Name': "Coca Cola", 'Description': 'Drinks', 'Price': 1.50, 'Stock': 25, 'Expiry Date': '27/05/21'}, 4: {'Item Name': "Dried Cha Soba", 'Description': 'Noodles & Pasta', 'Price': 3.75, 'Stock': 25, 'Expiry Date': '27/05/22'}, 5: {'Item Name': "Chinese Cabbage", 'Description': "Vegetable", 'Price': 1.50, 'Stock': 12, 'Expiry Date': '8/7/2020'} }something = []for i in Stock: something.append(Stock[i]['Item Name']) something.append(Stock[i]['Stock'])print(something)x = 0while something != "": for i in something: x += 1 newsomething = something[x], something[x+1]print(newsomething)