MacUsers
MacUsers

Reputation: 2229

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. 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":{"-":{...}}}}}. Any idea how can I get this thing right? cheers!!

Upvotes: 0

Views: 76

Answers (1)

wflynny
wflynny

Reputation: 18521

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).

Upvotes: 1

Related Questions