【问题标题】:comparing values from dictionary with same key python比较具有相同键python的字典中的值
【发布时间】:2022-11-29 06:19:59
【问题描述】:

下面是一本名为 total_per_person 的字典,它映射了一个人一周内的总支出

{'Edith': 79.24, 'Carol': 176.05, 'Hannah': 90.45, 'Frank': 66.6, 'Alice': 64.10, 'Ingrid': 59.45, 'Bob': 103.50, 'Gertrude': 107.45, 'Dave': 62.24}

下面是另一个名为 name_to_budget 的字典,它映射了一个人的每周预算:

{'Alice': 62.12, 'Bob': 40.34, 'Carol': 46.69, 'Dave': 37.79, 'Edith': 95.39, 'Frank': 32.87, 'Gertrude': 29.13, 'Hannah': 24.21, 'Ingrid': 91.19}

我如何比较这些值并确定它们是超出预算还是低于预算?我应该做一个功能让它更容易吗?

【问题讨论】:

  • 你试过写功能首先 - 你能分享代码吗?你在哪里遇到问题?
  • 需要考虑的事情:你能保证第一本词典在第二本词典中总是有相应的条目吗?你能保证第二个字典在第一个字典中总是有对应的条目吗?如果你不能做出这些保证,你想做什么?

标签: python dictionary compare


【解决方案1】:

您需要遍历键并比较两个字典上的每个键。 dict.keys() 返回包含所有键的列表。

此代码 sn-ps 还考虑了相应的预算,并确保密钥位于带有 in 运算符的第二个字典中。

total_per_person = {'Edith': 79.24, 'Carol': 176.05, 'Hannah': 90.45, 'Frank': 66.6, 'Alice': 64.10, 'Ingrid': 59.45, 'Bob': 103.50, 'Gertrude': 107.45, 'Dave': 62.24, 'Alex': 12.12}

name_to_budget = {'Alice': 62.12, 'Bob': 40.34, 'Carol': 46.69, 'Dave': 37.79, 'Edith': 95.39, 'Frank': 32.87, 'Gertrude': 29.13, 'Hannah': 24.21, 'Ingrid': 91.19}

compared_to_budget = {}

for key in total_per_person.keys():
    if key not in name_to_budget:
        compared_to_budget[key] = "missing" # Not in total_per_person dict
        break
    if total_per_person[key] == name_to_budget[key]:
        compared_to_budget[key] = "same"
    elif total_per_person[key] > name_to_budget[key]:
        compared_to_budget[key] = "under"
    else:
        compared_to_budget[key] = "over"

print(compared_to_budget)

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    相关资源
    最近更新 更多