从Python中的元组中的字典访问项目

时间:2020-05-04 17:27:53

标签: python python-3.x list dictionary tuples

假设我有一个如下所示的元组:

[('Cheeseburger', 'Entree', {'Buns': 1, 'Tomato': 1, 'Lettuce': 3, 'Onion': 1}), ('Salad', 'Entree', {'Buns': 0, 'Tomato': 2, 'Lettuce': 4, 'Onion': 3}), ...]

如何访问字典中的值以将它们加起来。字典在元组列表中。

例如,我正在寻找每种食品的总和(例如,芝士汉堡:6,色拉:7)。

2 个答案:

答案 0 :(得分:1)

假设每个元组中的字典项位于索引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}

答案 1 :(得分:1)

在这种情况下,您可以将其视为多维列表 并访问元素

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

希望这会有所帮助

相关问题