Python在多维字典中添加数据

标签 python

while (E > 0):
    line = raw_input("enter edges : ")
    data = line.split()
    mygraph[data[0]] = {data[1] : data[2]} //this line 
    print mygraph
    E-=1

所需的数据结构:

mygraph = { 
        'B': {'A': 5, 'D': 1, 'G': 2}
        'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5}}

我想为同一个键添加多个条目,例如 但 mycode 只为一个节点取一个值,然后替换 条目。如何做到这一点?

最佳答案

您需要首先为键 data[0] 添加一个空字典(如果它尚不存在),然后向其中添加值。否则你每次循环时都会将其清除。

两种常用的方法是使用 setdefault在普通字典上:

mygraph.setdefault(data[0], {})[data[1]] = data[2]

或使用collections.defaultdict其中默认值是空字典:

>>> from collections import defaultdict

>>> mygraph = defaultdict(dict)

>>> edges = [[1, 2, 3], [1, 3, 6]]
>>> for edge in edges:
...     mygraph[edge[1]][edge[2]] = edge[3]

>>> mygraph
{1: {2: 3,
     3: 6}}

关于Python在多维字典中添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32919331/

相关文章:

python - Python 中的正则表达式无法正确匹配

python - 如何获得张量的值? Python

python - 使用 turtle 图形的谢尔宾斯基三角形递归

python - django 有效地服务 robots.txt

python - python中的Unicode-Ascii混合字符串

python - 追加后如何打印列表中的所有元素?

python - 如何验证传递参数的总数?

python - Python 3 中的输入变量

python - 为什么 -ve int 的除法值与 +ve one 不同?

python - 如何将 HTML 与 Django 集成?