[英]how to create a multilevel dictionary
It must be a simple thing but can't get my head around it. 这一定是一件简单的事情,但我无法理解。 Part of my script does this:
我的脚本的一部分执行此操作:
myDict = {}
for dev in self.dmd.Devices():
device = dev.id
collector = dev.getPerformanceServerName()
instances = [ inst.id for inst in dev.instances() ]
and from there, I want to create a dictionary like this: 从那里,我想创建一个像这样的字典:
{
"EC2-test-eip-alloc": {
"mon511.backbc.local": [
"i-1828ca57",
"i-372d3978"
]
}
....
....
}
where EC2-test-eip-alloc => device
, mon511.backbc.local => collector
and ["i-1828ca57","i-372d3978"] => instances
. 其中EC2-test-eip-alloc =>
device
, mon511.backbc.local => collector
和[“ i-1828ca57”,“ i-372d3978”] => instances
。 I tried with: 我尝试了:
inDict = reduce(lambda d, k: d.setdefault(k, {}), device, myDict)
inDict.setdefault(collector, instances)
but getting a very strange result, where every character of device
is being taken as keys, like this: {"E":{"C":{"2":{"-":{...}}}}}
. 但是得到一个非常奇怪的结果,其中
device
每个字符都被当作键,例如: {"E":{"C":{"2":{"-":{...}}}}}
。 Any idea how can I get this thing right? 知道我该怎么做吗? cheers!!
干杯!!
To reiterate my comment above, change 要重申我在上面的评论,请更改
inDict = reduce(lambda d, k: d.setdefault(k, {}), device, myDict)
to 至
inDict = reduce(lambda d, k: d.setdefault(k, {}), (device,), myDict)
so that reduce iterates through ('device', )
(which yields 'device', StopIteration
) instead of 'device' (which yields 'd', 'e', 'v', 'i', 'c', 'e', StopIteration
). 从而使reduce通过
('device', )
(产生'device', StopIteration
)而不是'device'(产生'd', 'e', 'v', 'i', 'c', 'e', StopIteration
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.