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:
- Incorrect data structure handling: You were creating a list
aof dictionaries and trying to usej.update(a), butupdate()expects a dictionary, not a list. This would throw aTypeError. - Resetting the accumulator: The
a = []line was inside the inner loop, so it reset every time you checked a newtest1entry, preventing you from accumulating multiple matches. - Missing name collection: You didn't handle the
namesfield at all, which is part of the expected output. - Overwriting instead of appending: You weren't building up lists for
countryandstate—you were trying to add individual dictionaries instead of combining values into lists.
Notes
- We use
enumerate()to get both the index and entry fromtest2, allowing us to replace the original entry with the updated one. extend()is used fornamesbecause eachtest1entry'snamesis a list, and we want to add all its elements tocombined_names.append()is used forcountryandstatesince each is a single string value pertest1entry.
内容的提问来源于stack exchange,提问作者louis
相关产品推荐
相关产品推荐

