向词典中的列表添加条目

2024-03-29 04:57:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于以下方面的问题: 假设我有这样一个数据结构

shelfFile['Test']这是搁置文件中的字典。 我使用shelfFile['Test'] = {"January":["Test1","Test2"]}向它添加了一些值 现在,当我想使用shelfFile['Test']['January'].append()添加Test3时,它不起作用,它只返回原始值“Test1”和“Test2”。我也试过使用

shelfFile['test'].setdefault('January', []).append('Test3')

但这并不能很好地工作,这是因为字典/元组的任何可变性吗?也许有人可以推荐一些更合适的替代数据结构?“Test”条目是永久的,月份条目也是永久的,尽管每个月都会添加一个新条目。可以随时添加或删除“Test1”、“Test2”。你知道吗

感谢您的帮助!你知道吗


Tags: 文件test数据结构字典条目元组test1test2
1条回答
网友
1楼 · 发布于 2024-03-29 04:57:44

根据^{} module documentation

Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).

d = shelfFile['Test']         # extract a copy
d['January'].append('Test3')  # mutate
shelfFile['Test'] = d         # stores the copy right back, to persist it

相关问题 更多 >