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
相关产品推荐
相关产品推荐

