MST

星途 面试题库

面试题:Python字典合并与更新的复杂应用场景

假设有两个字典,第一个字典存储了不同城市的商品基本价格,第二个字典存储了特定城市对某些商品的价格调整(可能是加价或减价)。请编写一个函数,该函数接收这两个字典作为参数,返回一个合并后的字典,其中包含每个城市每种商品的最终价格。同时要考虑到价格调整字典中可能存在商品在基本价格字典中不存在的情况,需要对此进行合理处理。
15.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def merge_price_dicts(base_prices, price_adjustments):
    result = {}
    for city, base_prices_dict in base_prices.items():
        if city not in result:
            result[city] = {}
        for product, base_price in base_prices_dict.items():
            if city in price_adjustments and product in price_adjustments[city]:
                result[city][product] = base_price + price_adjustments[city][product]
            else:
                result[city][product] = base_price
    for city, adjustment_dict in price_adjustments.items():
        if city not in result:
            result[city] = {}
        for product, adjustment in adjustment_dict.items():
            if product not in result[city]:
                result[city][product] = adjustment
    return result