Python字典切片方法咨询及字典列表遍历异常解决
Hey there! Let's tackle your two questions step by step—first fixing that annoying traversal error, then covering how to do "slicing" with dictionaries (since they don't work exactly like lists).
1. Why Your Traversal Code Is Throwing an Error (and How to Fix It)
Your code uses for i in range(0,20): print(d[i]), but look at your dictionary list: it only has 3 elements (indices 0, 1, 2). Trying to access d[3] to d[19] will trigger an IndexError: list index out of range because those positions don't exist.
Here are 3 solid fixes, depending on what you need:
- Simplest: Traverse the list directly (no need for indices):
d = [{'model': 're_catalogue.component', 'pk': 1, 'fields': {'name': 'Solar modules', 'name_el': 'Φωτοβολταικά πλαίσια', 'name_de': 'Solarmodul'}}, {'model': 're_catalogue.component', 'pk': 2, 'fields': {'name': 'DC cables', 'name_el': 'DC καλώδια', 'name_de': 'DC-Kabel'}}, {'model': 're_catalogue.component', 'pk': 3, 'fields': {'name': 'DC combiner boxes', 'name_el': 'DC πίνακες', 'name_de': 'DC-Anschlussgehäuse'}}] for item in d: print(item) - If you need indices too: Use
enumerate()to get both index and element:for idx, item in enumerate(d): print(f"Index {idx}: {item}") - If you really want to loop up to 20 but avoid errors: Cap the range at the list's length:
# This will only loop through existing elements (0 to 2 in your case) for i in range(min(20, len(d))): print(d[i])
2. How to "Slice" a Dictionary in Python
Dictionaries aren't sequence types like lists, so they don't support the [start:end] slicing syntax directly. But you can replicate slicing behavior by working with their keys (or items) as a list:
Option 1: Slice by key position (Python 3.7+ preserves insertion order)
If you want the first N key-value pairs (or a range of them), convert the dictionary's keys to a list, slice that list, then build a new dictionary:
# Example with one of your 'fields' dictionaries sample_fields = {'name': 'Solar modules', 'name_el': 'Φωτοβολταικά πλαίσια', 'name_de': 'Solarmodul'} # Get first 2 key-value pairs sliced_fields = {k: sample_fields[k] for k in list(sample_fields.keys())[:2]} print(sliced_fields) # Output: {'name': 'Solar modules', 'name_el': 'Φωτοβολταικά πλαίσια'}
Option 2: Slice the entire list of dictionaries
If you actually wanted to slice the list of dictionaries itself (e.g., get the first 2 dictionaries in your list), that's easy with list slicing:
sliced_dictionary_list = d[:2] for item in sliced_dictionary_list: print(item)
Option 3: Slice by specific keys (not position)
If you want to pick specific keys instead of positions, just explicitly select them:
selected_fields = {k: sample_fields[k] for k in ['name', 'name_de']} print(selected_fields) # Output: {'name': 'Solar modules', 'name_de': 'Solarmodul'}
内容的提问来源于stack exchange,提问作者George

