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

Python中如何将变量作为字典键动态创建嵌套字典?

问题分析与解决方案

你的代码主要存在两个问题:

  • 函数内的dataStore是局部变量,你在函数里重新创建了一个新字典,完全没修改全局的dataStore
  • 最后print(datastore)是大小写错误,Python变量名区分大小写,正确写法是print(dataStore)

另外你担心的「用变量作为字典键」的语法是完全正确的,Python支持直接用变量作为字典键,不需要转义或额外加引号。

修正后的代码

dataStore = {}

def addLocationToDataStore(location):
    # 直接给全局字典添加新的location键,而非重新创建局部字典
    dataStore[location] = {
        'teamChatMessageCount.staff': 0, 
        'privateChatMessageCount.staff': 0, 
        'callCount.staff': 0, 
        'meetingCount.staff': 0, 
        'meetingsOrganizedCount.staff': 0, 
        'adHocMeetingsOrganizedCount.staff': 0, 
        'adHocMeetingsAttendedCount.staff': 0, 
        'urgentMessages.staff': 0, 
        'postMessages.staff': 0, 
        'replyMessages.staff': 0, 
        'audioDuration.staff': 0, 
        'videoDuration.staff': 0, 
        'screenShareDuration.staff': 0,
        'teamChatMessageCount.student': 0, 
        'privateChatMessageCount.student': 0, 
        'callCount.student': 0, 
        'meetingCount.student': 0, 
        'meetingsOrganizedCount.student': 0, 
        'adHocMeetingsOrganizedCount.student': 0, 
        'adHocMeetingsAttendedCount.student': 0, 
        'urgentMessages.student': 0, 
        'postMessages.student': 0, 
        'replyMessages.student': 0, 
        'audioDuration.student': 0, 
        'videoDuration.student': 0, 
        'screenShareDuration.student': 0
    }

addLocationToDataStore("test") 
print(dataStore)

补充说明

如果一定要通过global声明使用全局变量(不推荐,易引发变量混淆),代码可改为:

dataStore = {}

def addLocationToDataStore(location):
    global dataStore  # 声明要操作全局的dataStore变量
    dataStore = {location: {...}}  # 此写法会覆盖整个全局字典,仅适合初始化场景

addLocationToDataStore("test") 
print(dataStore)

但第一种直接给字典赋值键的方式更灵活,后续可多次调用函数添加不同location,不会覆盖已有内容。

内容的提问来源于stack exchange,提问作者Nathan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:52:54