You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何用嵌套字典dict2更新合并dict1?

Solution for Merging Nested Dictionaries in Python

Got it, let's tackle this nested dictionary merge problem. The goal is to update dict1 with dict2—adding new outer keys if they don't exist, and merging inner dictionaries (overwriting existing values and adding new ones) when outer keys match. Here's a straightforward approach that gives you exactly the final_dict you want:

# Define your input dictionaries
dict1 = {'https://site1.com': {'React': None, 'Drupal': '5.1', 'python': None}}
dict2 = {'https://site1.com': {'React': '6.0', 'Drupal': '5.3', 'PHP': '7'}, 'https://site2.com': {'Rails': '6.1'}}

# Create a copy of dict1 to avoid modifying the original dictionary
final_dict = dict1.copy()

# Iterate through each entry in dict2
for site_url, tech_versions in dict2.items():
    if site_url in final_dict:
        # Update the inner dictionary: overwrite existing keys, add new ones
        final_dict[site_url].update(tech_versions)
    else:
        # Add the new site and its tech versions to final_dict
        final_dict[site_url] = tech_versions

# Verify the result
print(final_dict)

How this works:

  • final_dict = dict1.copy(): We start by making a copy of dict1 so we don't alter the original data (this is a best practice to avoid unintended side effects).
  • Loop through dict2: For each website URL and its corresponding technology version dictionary:
    • If the URL is already present in final_dict, we use the update() method on the inner dictionary. This method automatically replaces existing values (like updating React from None to 6.0 and Drupal from 5.1 to 5.3) and adds new key-value pairs (like the PHP: '7' entry).
    • If the URL isn't in final_dict, we simply add the entire key-value pair (like https://site2.com and its Rails: '6.1' data).

Running this code will output exactly the final_dict you specified:

{'https://site1.com': {'React': '6.0', 'Drupal': '5.3', 'python': None, 'PHP': '7'}, 'https://site2.com': {'Rails': '6.1'}}

内容的提问来源于stack exchange,提问作者Arbazz Hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:44:29