【问题标题】:Accessing items from a dictionary within a tuple in Python在 Python 的元组中访问字典中的项目
【发布时间】:2020-05-04 17:27:53
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您是否正在寻找所有字典中所有值的总和,即在这种情况下为 14?
  • @ArkistarvhKltzuonstev 抱歉 - 已修复
  • @DarrylG 抱歉 - 已修复

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


【解决方案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

希望对你有帮助

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 2019-11-16
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多