如何在for循环中创建嵌套列表并添加到字典及修改指定元素?
Fixing Your Dictionary of Lists Code (and the Unpack Error)
Let's break down what's going wrong with your code first, then walk through the correct implementation step by step.
Key Issues in Your Original Code
- Shared List Reference: Using
dict.fromkeys(range(0,6), [])creates a dictionary where every key points to the same list object. Any change to one key's list will affect all others—this is a common gotcha withfromkeyswhen using mutable values like lists. - Incorrect Dictionary Traversal: When you loop over
dict_of_listsdirectly (for key, value in dict_of_lists:), you're only iterating over the dictionary's keys, not key-value pairs. Each iteration gives you a single integer (the key), which can't be unpacked intokey, value—that's exactly why you get thecannot unpack non-iterable int objecterror. You need to usedict_of_lists.items()if you want both key and value, or just loop over keys directly here. - Overwriting Lists Instead of Appending: Your inner loop
for li in range(5): dict_of_lists[key] = [li,0,0]replaces the entire list forkeywith a new single list each time. By the end of the loop, you'll only have[4,0,0]instead of 5 sub-lists. You need to append each new sub-list instead of assigning. - Undefined Variables: You reference
itemandpricebut don't define them—we'll assume these are pre-existing dictionaries with values for each index/key (we'll use example values in the fix).
Correct Implementation
Here's the revised code that meets your requirements:
# Define example values for item and price (adjust these to your actual data) item = {1: 10, 2: 20} # Values corresponding to sub-list indices 1 and 2 price = {key: 5 for key in range(6)} # Price value for each dictionary key # Create a dictionary where each key has its own empty list (no shared references!) dict_of_lists = {key: [] for key in range(6)} # Populate each key's list with 5 sub-lists for key in dict_of_lists: # Generate and append 5 sub-lists: [li, 0, 0] for li from 0 to 4 for li in range(5): dict_of_lists[key].append([li, 0, 0]) # Modify the last value of sub-lists at indices 1 and 2 for wi in [1, 2]: # Calculate the 'x' value using your formula dict_of_lists[key][wi][2] = item[wi] * price[key] # Print the result to verify for key, lists in dict_of_lists.items(): print(f"{key}: {lists}")
What This Code Does
- Independent Lists: The dictionary comprehension
{key: [] for key in range(6)}ensures every key gets its own unique empty list, so changes to one key's lists don't affect others. - Appending Sub-Lists: Using
.append()adds each new[li,0,0]to the key's list, resulting in exactly 5 sub-lists per key. - Targeted Modification: We access
dict_of_lists[key][wi][2]to update the third element (index 2) of the sub-list at positionwi(1 or 2) for each key, using your calculation formula.
Example Output
With the example item and price values above, you'll get:
0: [[0, 0, 0], [1, 0, 50], [2, 0, 100], [3, 0, 0], [4, 0, 0]] 1: [[0, 0, 0], [1, 0, 50], [2, 0, 100], [3, 0, 0], [4, 0, 0]] 2: [[0, 0, 0], [1, 0, 50], [2, 0, 100], [3, 0, 0], [4, 0, 0]] 3: [[0, 0, 0], [1, 0, 50], [2, 0, 100], [3, 0, 0], [4, 0, 0]] 4: [[0, 0, 0], [1, 0, 50], [2, 0, 100], [3, 0, 0], [4, 0, 0]] 5: [[0, 0, 0], [1, 0, 50], [2, 0, 100], [3, 0, 0], [4, 0, 0]]
内容的提问来源于stack exchange,提问作者Dylan_w
相关产品推荐
相关产品推荐

