Вы можете использовать **kwargs
для объединения словарей, поскольку оно расширяет содержимое словаря как набор пар ключ-значение. И мы можем сделать сравнение с keys
, имеющими несколько value
s в результирующем словаре,
import ast
def compare_prices(dict1, dict2):
temp1 = ast.literal_eval(dict1)
temp2 = ast.literal_eval(dict2)
tempDict = {**temp1, **temp2} # two or more Dicts merged using **kwargs
for key, value in tempDict.items():
if key in temp1 and key in temp2:
tempDict[key] = min([value, temp1[key]]) # sets the minimum value
return tempDict
Выходные данные ,
print(compare_prices(x, y))
#{'45': 220.0, '43': 220.0, '44.5': 220.0, '39': 370.0, '47': 300.0, '46': 225.0, '44': 220.0, '47.5': 265.0, '40.5': 395.0, '42.5': 230.0, '42': 300.0, '38': 375.0, '45.5': 290.0, '37.5': 355.0, '41': 345.0, '38.5': 375.0, '36': 345.0, '36.5': 360.0, '48.5': 275.0, '40': 380.0, '48': 287, '49.5': 567, '50.5': 850, '51.5': 399, '49': 386}
Если Вы хотите отсортированный словарь, который вы можете использовать OrderedDict
из collections
библиотеки
import ast
from collections import OrderedDict
def compare_prices(dict1, dict2):
temp1 = ast.literal_eval(dict1)
temp2 = ast.literal_eval(dict2)
tempDict = {**temp1, **temp2} # two or more Dicts merged using **kwargs
for key, value in tempDict.items():
if key in temp1 and key in temp2:
tempDict[key] = min([value, temp1[key]]) # sets the minimum value
return OrderedDict(sorted(tempDict.items(), key=lambda t: t[0]))
Вывод ,
print(compare_prices(x, y))
#OrderedDict([('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)])