August 22, 2012

November 25, 2019

Nested, infinite dictionary in python

Some time ago I have rewritten my own project from PHP to Python. I needed something similar to arrays in PHP - "automatic" generation of the values (and the keys) which don't exist.

PHP example.

<?php
$test = array();
print_r($test);
$test['a']['b'] = 1;
print_r($test);
$test['a']['b'] += 1;
print_r($test);
$test['b']['a'] += 1;
print_r($test);
?>

Test.

eshlox@eshlox ~/Temp/php $ php test.php
Array
(
)
Array
(
[a] => Array
(
[b] => 1
)
)
Array
(
[a] => Array
(
[b] => 2
)
)
Array
(
[a] => Array
(
[b] => 2
)
[b] => Array
(
[a] => 1
)
)

Solution.

class NestedDict(dict):
def __getitem__(self, key):
if key in self:
return self.get(key)
return self.setdefault(key, NestedDict())
def __add__(self, other):
return other
def __sub__(self, other):
return other
>>> test = NestedDict()
>>> test
{}
>>> test['a']['b'] = 1
>>> test
{'a': {'b': 1}}
>>> test['a']['b'] += 1
>>> test
{'a': {'b': 2}}
>>> test['b']['a'] += 1
>>> test
{'a': {'b': 2}, 'b': {'a': 1}}
© 2020 Przemysław Kołodziejczyk