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

LPTHW教程中用方括号创建字典报错,如何解决?

Fixing the Dictionary Creation Error in 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:

  1. Create an empty dictionary:

    # Option 1: Preferred curly brace syntax
    my_dict = {}
    
    # Option 2: Using the dict() constructor
    my_dict = dict()
    
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:24:00