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 ofdict1so 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 theupdate()method on the inner dictionary. This method automatically replaces existing values (like updating React fromNoneto6.0and Drupal from5.1to5.3) and adds new key-value pairs (like thePHP: '7'entry). - If the URL isn't in
final_dict, we simply add the entire key-value pair (likehttps://site2.comand itsRails: '6.1'data).
- If the URL is already present in
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
相关产品推荐
相关产品推荐

