LPTHW教程中用方括号创建字典报错,如何解决?
Hey there! Let's clear up this confusion right away—what you're seeing is likely a typo (or a momentary slip-up in the tutorial), because square brackets [] create lists in Python, not dictionaries. That's exactly why you're hitting errors when trying to use that "dict" like a real dictionary.
The Core Issue
When you write:
# Wrong: This creates a LIST, not a dictionary dict = [] config = []
You're making empty lists, not dictionaries. If you later try to do dictionary-specific operations like config['api_key'] = '123abc', Python will throw a TypeError because lists only accept integer/slice indices, not string keys.
The Correct Way to Create Dictionaries
In Python, dictionaries use curly braces {}. Here's how to fix your code:
Create an empty dictionary:
# Option 1: Preferred curly brace syntax my_dict = {} # Option 2: Using the dict() constructor my_dict = dict()Create a config dictionary (like your project example):
# Correct config dictionary with key-value pairs config = { 'debug': True, 'server_port': 8080, 'database': { 'host': 'localhost', 'username': 'dev_user' } }
Testing It Out
Once you use {} instead of [], you can safely perform dictionary operations without errors:
# This works now! config['debug'] = False print(config['server_port']) # Outputs 8080
It's easy to mix up brackets when you're starting out—don't worry, we've all been there. Just remember:
[]= Lists (ordered, index-based collections){}= Dictionaries (unordered, key-value mappings)
内容的提问来源于stack exchange,提问作者azizbro

