基于匹配值合并字典列表:匹配追加字段,无匹配保留原项
How to Merge Two Dictionary Lists by Matching Fields Without Duplicate Entries
Let's break down your problem and fix the duplicate output issue step by step.
Problem Statement
You want to merge two lists of dictionaries:
- For each entry in the
fruitlist, match it with entries in thetypelist using thefruit['Name']andtype['Fruit']fields. - If a match is found, add the corresponding
Heightfield to the fruit dictionary. - If no match exists, keep the original fruit dictionary as-is.
- Your current nested loop code is producing duplicate entries, and you need a correct implementation.
Initial Data
fruit = [ {'Type':'Tree', 'Name':'Pear', 'Color':'Red,Green'}, {'Type':'Bush', 'Name':'Raspberry', 'Color':'Red,White'}, {'Type':'Tree', 'Name':'Apple', 'Color':'Red,Green'} ] # Note: `type` is a built-in Python keyword, so I'll rename it to `fruit_types` for best practice fruit_types = [ {'Type':'Tree', 'Fruit':'Pear', 'Height':'25ft'}, {'Type':'Tree', 'Fruit':'Apple', 'Height':'15ft'}, {'Type':'Root', 'Fruit':'Carrot', 'Height':'2ft'} ]
Why Your Original Code Causes Duplicates
Looking at your attempt:
combined = [] for i in fruit: for x in type: if i['Name'] == x['Name']: # ❌ Wrong field comparison (should be x['Fruit']) out = i out['Height'] = x['Height'] combined.append(out) else: combined.append(i)
Three key issues here:
- Duplicate Appends: For every entry in
fruit, you loop through all entries intype. Each time there's no match, you append the fruit dictionary tocombined—this means one fruit entry gets added multiple times (once for every non-matchingtypeentry). - Incorrect Field Match: You're comparing
i['Name']tox['Name'], but thetypelist uses theFruitfield, notName. This would prevent matches even if the values are correct. - Mutable Dictionary Reference: You're modifying the original
idictionary directly instead of creating a copy, which can lead to unintended side effects on the originalfruitlist.
Correct Solutions
Solution 1: Use a Mapping Dictionary (Most Efficient)
First, convert the fruit_types list into a dictionary where keys are the Fruit values and values are the corresponding Height. This reduces the time complexity from O(n*m) to O(n+m), making it much faster for large datasets.
# Build a lookup map for Fruit -> Height height_lookup = {item['Fruit']: item['Height'] for item in fruit_types} combined = [] for fruit_item in fruit: # Create a copy of the original dictionary to avoid modifying the original data merged_item = fruit_item.copy() # Check if the fruit's Name exists in our lookup map if fruit_item['Name'] in height_lookup: merged_item['Height'] = height_lookup[fruit_item['Name']] combined.append(merged_item) print(combined)
Solution 2: Fixed Nested Loop
If you prefer to use a nested loop, adjust the logic to only append each fruit entry once, after checking all possible matches:
combined = [] for fruit_item in fruit: merged_item = fruit_item.copy() # Copy to avoid modifying original matched = False for type_item in fruit_types: if fruit_item['Name'] == type_item['Fruit']: merged_item['Height'] = type_item['Height'] matched = True break # Exit inner loop once a match is found combined.append(merged_item) # Append only once per fruit entry print(combined)
Expected Output
Both solutions will produce your desired result:
combined = [ {'Type':'Tree', 'Name':'Pear', 'Color':'Red,Green', 'Height':'25ft'}, {'Type':'Bush', 'Name':'Raspberry', 'Color':'Red,White'}, {'Type':'Tree', 'Name':'Apple', 'Color':'Red,Green', 'Height':'15ft'} ]
内容的提问来源于stack exchange,提问作者csling
相关产品推荐
相关产品推荐

