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

Python中基于另一字典列表更新字典列表的技术实现问题

Solution to Update test2 Based on test1 Country Matches

Let's break down how to achieve your expected output. The goal is to iterate through each entry in test2, collect all matching entries from test1 where the country appears in test2's list_of_countries, then combine the relevant fields into lists while preserving the code from test2.

Correct Implementation Code

test1 = [
    {'names': ['a', 'b', 'c'], 'country': 'USA', 'state': 'Texas'},
    {'names': ['d', 'e', 'f'], 'country': 'Australia', 'state': 'Melbourne'},
    {'names': ['i', 'j', 'k'], 'country': 'canada', 'state': 'Toronto'},
    {'names': ['l', 'm', 'n'], 'country': 'Austria', 'state': 'Burgenland'}
]
test2 = [
    {'code': 4286, 'list_of_countries': ['USA', 'Australia', 'Colombia', 'Denmark', 'Greece', 'Iceland']},
    {'code': 4287, 'list_of_countries': ['Texas', 'Argentina', 'Austria', 'Bangladesh', 'canada']}
]

# Process each item in test2
for idx, t2_entry in enumerate(test2):
    # Initialize empty lists to collect combined data
    combined_names = []
    combined_countries = []
    combined_states = []
    
    # Check each entry in test1 for country matches
    for t1_entry in test1:
        t1_country = t1_entry['country']
        if t1_country in t2_entry['list_of_countries']:
            # Extend names (since names is a list of multiple values)
            combined_names.extend(t1_entry['names'])
            # Append single country and state values
            combined_countries.append(t1_country)
            combined_states.append(t1_entry['state'])
    
    # Create the updated entry with combined data and preserved code
    updated_entry = {
        'names': combined_names,
        'country': combined_countries,
        'state': combined_states,
        'code': t2_entry['code']
    }
    
    # Replace the original test2 entry with the updated one
    test2[idx] = updated_entry

# Verify the result
print(test2)

Why Your Original Code Didn't Work

Your original approach had a few key issues:

  1. Incorrect data structure handling: You were creating a list a of dictionaries and trying to use j.update(a), but update() expects a dictionary, not a list. This would throw a TypeError.
  2. Resetting the accumulator: The a = [] line was inside the inner loop, so it reset every time you checked a new test1 entry, preventing you from accumulating multiple matches.
  3. Missing name collection: You didn't handle the names field at all, which is part of the expected output.
  4. Overwriting instead of appending: You weren't building up lists for country and state—you were trying to add individual dictionaries instead of combining values into lists.

Notes

  • We use enumerate() to get both the index and entry from test2, allowing us to replace the original entry with the updated one.
  • extend() is used for names because each test1 entry's names is a list, and we want to add all its elements to combined_names.
  • append() is used for country and state since each is a single string value per test1 entry.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 09:02:27