Python字典-如何防止新值覆盖以前的值? [英] Python dictionaries-How to keep the new value from overwriting the previous value?

查看:24
本文介绍了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字典-如何防止新值覆盖以前的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆