[英]Python adding data in multi-dimensional dictionary
while (E > 0):
line = raw_input("enter edges : ")
data = line.split()
mygraph[data[0]] = {data[1] : data[2]} //this line
print mygraph
E-=1
Desired data structure: 所需的数据结构:
mygraph = {
'B': {'A': 5, 'D': 1, 'G': 2}
'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5}}
i want to add multiple entries for same key like but mycode is taking only one value for one node and then replacing the entries.How to do that? 我想为相同的键添加多个条目,但mycode仅为一个节点取一个值,然后替换条目。如何做到这一点?
You need to first add an empty dictionary for the key data[0]
if it doesn't already exist, then add the values to it. 您需要首先为键
data[0]
添加一个空字典(如果尚不存在),然后向其中添加值。 Otherwise you just wipe out it out every time you loop. 否则,您每次循环时都将其清除。
The two usual ways are either to use setdefault
on a normal dictionary: 两种常用方法是在普通字典上使用
setdefault
:
mygraph.setdefault(data[0], {})[data[1]] = data[2]
or use collections.defaultdict
where the default is an empty dictionary: 或使用
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}}
Replace this line: 替换此行:
mygraph[data[0]] = {data[1] : data[2]}
with these: 用这些:
if not data[0] in mygraph:
mygraph[data[0]] = {}
mygraph[data[0]][data[1]] = data[2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.