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

查看:737
本文介绍了Python字典 - 如何保持新值覆盖以前的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个名为First(如First Name)的字典,它将存储许多通过一个函数存储在字典中的名字。这个想法是字典可以支持多个名称,



所以这里是我的问题:



当我添加字典的名称,然后我通过该函数添加第二个,以前的名称被最后覆盖。我该如何修补?我知道它涉及字典中的字典或嵌套条件。这是我的代码:

  def store(data,value):
data ['Names'] = {}
data ['Names'] ['first'] = {}
data ['Names'] ['first'] = {value}
pre>

解决方案

转动 data ['Names'] ['first'] 在列表中并附加到它:

  data ['Names'] = {} 
data ['Names '] ['first'] = []

def store(data,value):
data ['Names'] ['first']。append(value)


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,

so here is my problem:

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}

解决方案

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天全站免登陆