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

基于匹配值合并字典列表:匹配追加字段,无匹配保留原项

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 fruit list, match it with entries in the type list using the fruit['Name'] and type['Fruit'] fields.
  • If a match is found, add the corresponding Height field 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:

  1. Duplicate Appends: For every entry in fruit, you loop through all entries in type. Each time there's no match, you append the fruit dictionary to combined—this means one fruit entry gets added multiple times (once for every non-matching type entry).
  2. Incorrect Field Match: You're comparing i['Name'] to x['Name'], but the type list uses the Fruit field, not Name. This would prevent matches even if the values are correct.
  3. Mutable Dictionary Reference: You're modifying the original i dictionary directly instead of creating a copy, which can lead to unintended side effects on the original fruit list.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:20:22