【问题标题】:python 3 adding multiple values under same key in dictionary [duplicate]python 3在字典中的同一键下添加多个值[重复]
【发布时间】:2019-04-27 09:50:54
【问题描述】:

我的代码有问题,尝试查找如何修复它并尝试了多种方法,但就是不行

这是我得到的:

with open("people-data.txt") as f:

children= {}
for line in f.readlines():
    parent, child = line.split("->")
    children[parent] = child

我尝试使用:children[parent].append(child) 和其他东西。

我的文件如下所示:

Mary->Patricia
Mary->Lisa
Patricia->Barbara

我想要的是,当我使用 children[Mary] 时,我得到了 ['Patricia', 'Lisa'],但我的代码所做的只是给出我的 'Lisa' 并覆盖 'Patricia'

【问题讨论】:

  • 应该是children[parent] = child。在您的情况下,您将存储密钥 "parent" 并覆盖它。
  • 对不起,我抄错了,让我改正
  • 您需要使用集合中的默认字典。
  • 当然会覆盖。 children[parent] = child 还会做什么?您需要在字典的每个值中保留列表,这可以通过使用children = defaultdict(list)children[parent].append(child) 轻松完成

标签: python python-3.x dictionary


【解决方案1】:

我尝试使用:children[parent].append(child)

只要您使用列表作为字典值,这将起作用。

最简单的解决方法是让孩子成为defaultdict,即

from collections import defaultdict
children = defaultdict(list)

然后使用

children[parent].append(child)

在您的代码中。

演示:

>>> from collections import defaultdict
>>> children = defaultdict(list)
>>> 
>>> children['Peter'].append('Bob')
>>> children['Peter'].append('Alice')
>>> children['Mary'].append('Joe')
>>> 
>>> children
defaultdict(list, {'Mary': ['Joe'], 'Peter': ['Bob', 'Alice']})

【讨论】:

  • 是的,别忘了:children[parent].append(child) 以获得完整的解决方案。
  • 谢谢,它现在正在创建我想要的东西,但问题是当我调用 children("Mary") 时,我发现它不可调用,我需要稍后使用这些值
  • @DávidKačmar children['Mary'].
  • 谢谢!!!!我爱你们!!或女孩:D 拯救了我的一天:D 非常感谢
猜你喜欢
  • 2021-04-30
  • 1970-01-01
  • 2015-02-16
  • 2013-04-13
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
相关资源
最近更新 更多