[英]Accessing items from a dictionary within a tuple in Python
假设我有一个元组,如下所示:
[('Cheeseburger', 'Entree', {'Buns': 1, 'Tomato': 1, 'Lettuce': 3, 'Onion': 1}), ('Salad', 'Entree', {'Buns': 0, 'Tomato': 2, 'Lettuce': 4, 'Onion': 3}), ...]
我如何访问字典中的值来添加它们。 字典在元组列表中。
例如,我正在寻找每种食物的总和(例如,芝士汉堡:6,沙拉:7)。
假设在每个元组中字典项的索引为 2,您可以简单地执行以下操作:
food_list = [('Cheeseburger', 'Entree', {'Buns': 1, 'Tomato': 1, 'Lettuce': 3, 'Onion': 1}),
('Salad', 'Entree', {'Buns': 0, 'Tomato': 2, 'Lettuce': 4, 'Onion': 3}), ...]
food_dict = {k[0] : sum(k[2].values()) for k in food_list}
在这种情况下,您可以将其视为多维列表并访问元素
list = [('Cheeseburger', 'Entree', {'Buns': 1, 'Tomato': 1, 'Lettuce': 3, 'Onion': 1}),
('Salad', 'Entree', {'Buns': 0, 'Tomato': 2, 'Lettuce': 4, 'Onion': 2})]
for i in range (len(list)):
for j in range (len(list[i])):
if type(list[i][j]) == dict:
x = list[i][j].items()
# Remaing operations that you want to perform based on your need
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.