首页 > 解决方案 > 比较两个保持最小值的字典值

问题描述

我正在尝试编写一个函数,该函数接受两个字典并返回一个合并的字典,其中包含两个字典中的所有键,如果两个字典中都存在任何键,则进行比较prices以保持最低值。

x = "{'45': 450, '43': 500, '44.5': 420, '39': 415, '47': 320, '46': 520, '44': 400, '47.5': 480, '40.5': 407, '42.5': 407, '42': 401, '38': 401, '45.5': 435, '37.5': 415, '41': 506, '38.5': 787, '36': 399, '36.5': 410, '48.5': 380, '40': 406, '48': 287, '49.5': 567, '50.5': 850, '51.5': 399, '49': 386}"
y = "{'36': 345.0, '36.5': 360.0, '37.5': 355.0, '38': 375.0, '38.5': 375.0, '39': 370.0, '40': 380.0, '40.5': 395.0, '41': 345.0, '42': 300.0, '42.5': 230.0, '43': 220.0, '44': 220.0, '44.5': 220.0, '45': 220.0, '45.5': 290.0, '46': 225.0, '47': 300.0, '47.5': 265.0, '48': 425.0, '48.5': 275.0, '49': 2000.0, '49.5': 1350.0, '51.5': 2000.0}"

我写了这个函数来做到这一点,但我相信它可以用更pythonic的方式编写

import ast
def compare_prices(dict1,dict2):
    temp1 = ast.literal_eval(dict1)
    temp2 = ast.literal_eval(dict2)
    for k,v in temp1.items():
        if k in temp2.keys():
            price = temp2[k] if temp2[k] else False
            if price:
                if v> price:
                    temp1[k] = price
                else:
                    temp1[k] = v
            else:
                temp1[k] = v
        else:
            temp1[k] = v
    for k,v in temp2.items():
        if k not in temp1.keys():
            try:
                temp1[k] = v if v else ''
            except TypeError:
                temp1[k] = v
    return dict(sorted(temp1.items()))

标签: pythondictionary

解决方案


我相信这会满足您的要求。它更简单,因为它使用一组键,因此set1.intersection(set2)包含两组中的所有键,因此它可以使用它来进行比较,并且set2-set1只包含那些唯一的set2,所以它们可以简单地移动到set1

def compare_prices(dict1,dict2):
    temp1 = ast.literal_eval(dict1)
    temp2 = ast.literal_eval(dict2)
    set1 = set(temp1.keys())
    set2 = set(temp2.keys())
    for k in set1.intersection(set2):
        if temp1[k] > temp2[k]:
            temp1[k] = temp2[k]
    for k in set2 - set1:
        temp1[k] = temp2[k]
    return dict(sorted(temp1.items()))

输出是:

print(compare_prices(x, y))
{'36': 345.0, '36.5': 360.0, '37.5': 355.0, '38': 375.0, '38.5': 375.0, '39': 370.0, '40': 380.0, '40.5': 395.0, '41': 345.0, '42': 300.0, '42.5': 230.0, '43': 220.0, '44': 220.0, '44.5': 220.0, '45': 220.0, '45.5': 290.0, '46': 225.0, '47': 300.0, '47.5': 265.0, '48': 287, '48.5': 275.0, '49': 386, '49.5': 567, '50.5': 850, '51.5': 399}

推荐阅读