Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python. Pushing values to the dictionary in dictionary

Tags:

python

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.

like image 257
Glueon Avatar asked Aug 27 '26 13:08

Glueon


1 Answers

a = collections.defaultdict(dict)
a['b']['c'] = 'd'

returns

defaultdict(<type 'dict'>, {'b': {'c': 'd'}})
like image 104
SlimJim Avatar answered Aug 30 '26 03:08

SlimJim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!