【问题标题】:How to create a nested dictionary with this given input in Python?如何在 Python 中使用给定的输入创建嵌套字典?
【发布时间】:2015-01-17 23:07:08
【问题描述】:

我在单独的行中给出了这个输入,我想创建一个嵌套图。

输入:

a b 3
b c 4
a c 10

所需的嵌套字典:

{'a': {
    'b': 3,
    'c': 10 },
 'b': {'c': 4 }
}

这是我的代码,但是它覆盖了相同的键。

for rec in range(2, num_lines):
    first, second, length = lines[rec].split()    
    d[first] = {}
    d[first][second] = length

【问题讨论】:

  • 使用哪种语言?蟒蛇?
  • 是的。 Python。谢谢。

标签: python dictionary nested key overwrite


【解决方案1】:

您只需要在将第一个键设置为字典之前检查并查看第一个键是否已经在字典中。

out = {}
for line in input:
    first, second, third in line.split()
    if not first in out:
        out[first] = {}
    out[first][second] = third

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 2019-11-29
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多