【问题标题】:implement dynamic nested dictionaries? [closed]实现动态嵌套字典? [关闭]
【发布时间】:2014-06-03 03:42:21
【问题描述】:
mother_dict=
     {'son_dict':{'Name':'Jason','Age':26},'daughter_dict':{'Name':'Emma','Age':19}}
father_dict={}
father_dict['Child']=mother_dict[son_dict]

我需要一种方法来根据输入将father_dict['Child'] 替换为来自mother_dict 的字典。 我试过删除father_dict的内容并用.update()的mother_dict的内容替换它们,但这当然会添加整个字典,我尝试使用input()向用户询问孩子,所以如果他们说'Jason'它将用son_dict替换'Child',但是当我进入有十个左右孩子的家庭时,需要十个函数,如果孩子的名字改变了,那么函数和字典都需要重新-书面。我已经挂断了使用输入从 Mother_dict 中获取特定字典并将其复制到 Father_dict。

【问题讨论】:

  • 您能否向我们展示您迄今为止所尝试的方法以及遇到的问题?
  • 有人可以解释为什么这个问题被否决了吗?如果这个问题已经存在于某个地方,或者我的措辞有问题,我想知道,这样我以后可以写出更好的问题。
  • 问题的问题(以及投反对票的可能原因)是您没有向我们提供任何有关您已尝试或未尝试的信息。我们不需要也不想要你的整个代码,我们想要一个SSCCE
  • 你的例子应该说father_dict['Child']=mother_dict['son_dict']吗?
  • 天哪,这些 cmets 中现在有两个 @dano 类型名称。即将在这里变得真正混乱。 OP,您向我们提供了您的代码,太好了。现在请向我们展示您尝试过的内容以及遇到的问题

标签: python python-3.x dictionary


【解决方案1】:

可能类似于以下内容?

choice = ''
mother_dict= {'son_dict':{'Name':'Jason','Age':26},'daughter_dict':{'Name':'Emma','Age':19}}
father_dict = {}
while choice not in mother_dict:
    choice = raw_input('Which dict do you want? ')

father_dict[choice] = mother_dict[choice]

此代码在输入有效(位于mother_dict 中)之前一直被输入,然后将该输入添加到father_dict

【讨论】:

  • 谢谢,这解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2020-04-02
相关资源
最近更新 更多