Reputation: 4027
I am getting values from some source using which I need to create a dictionary of dictionary.
To solve such a task in PHP I would just write a for
loop and:
$arr[ifIndex][$key] = $val
I do not need to bother if a $key
value really exists in my associative array - it will be created if it isn't.
In Python though you get a key error so I have to check that and add a dictionary if it isn't there:
if ifIndex in data:
data[ifIndex][entry] = val.prettyPrint()
else:
data[ifIndex] = { entry: val.prettyPrint() }
To me that looks very ugly and I think there is way of doing that as simple as in a PHP example.
Upvotes: 3
Views: 102
Reputation: 2272
a = collections.defaultdict(dict)
a['b']['c'] = 'd'
returns
defaultdict(<type 'dict'>, {'b': {'c': 'd'}})
Upvotes: 4