【发布时间】:2020-04-25 13:16:40
【问题描述】:
我正在尝试编写一个函数,它接收两个字典并返回一个合并的字典,其中包含两个字典中的所有键,如果两个字典中都存在任何键,则比较 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()))
【问题讨论】:
-
你想要的输出是什么?
-
@DirtyBit,猜猜标题中提到了预期的输出。
-
@dvlper 基于给定样本数据的显式输出样本比猜测要好
标签: python dictionary