Python dictionaries-How to keep the new value from overwriting the previous value?(Python字典-如何防止新值覆盖以前的值?)
问题描述
我想创建一个名为First"(如名字中)的字典,它将存储许多名字,这些名字都通过函数存储在字典中.思路是字典可以支持多个名字,
I want to create a Dictionary called "First" (as in First Name) that will store numerous first names which are all stored in the dictionary via a function. The idea is that the dictionary can support multiple names,
所以这是我的问题:
当我向字典中添加一个名字时,然后我通过函数添加第二个,之前的名字被最后一个覆盖.我该如何修补?我知道它涉及诸如字典中的字典或嵌套条件之类的东西.这是我的代码:
When I add a name to the dictionary, then I go to add a second one via the function, the previous name is overwritten by the last. How do I mend this? I know it involves something like a dictionary within a dictionary, or nested conditionals. Here is my code:
def store(data,value):
data['Names'] = {}
data['Names']['first'] = {}
data['Names']['first'] = {value}
推荐答案
将 data['Names']['first'] 转入一个列表并附加到它:
Turn data['Names']['first'] in a list and append to it:
data['Names'] = {}
data['Names']['first'] = []
def store(data, value):
data['Names']['first'].append(value)
这篇关于Python字典-如何防止新值覆盖以前的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python字典-如何防止新值覆盖以前的值?
基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
