Skip to content

Instantly share code, notes, and snippets.

@adeishs
Last active November 7, 2022 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeishs/c6581b3bd3959bd655e6daef9adac691 to your computer and use it in GitHub Desktop.
Save adeishs/c6581b3bd3959bd655e6daef9adac691 to your computer and use it in GitHub Desktop.
Multilevel Dictionaries in Python

As an experienced Perl programmer, I have been dealing with nested hashrefs of hashrefs. (Those not familiar with Perl: hashref is short for hash reference. Hash is also known as associative array.)

In Perl, we can just arbitrarily create hashrefs of hashrefs on the fly, e.g. hashref-hashref.pl

In Python, not so easy. Something like multilevel-dict-broken.py will give you a KeyError exception.

My friend Kamal Advani (thanks, man!) suggested something like multilevel-dict-solution.py to me.

Use at your own risk. I do not provide any support for this. You have my permission to copy it.

#!/usr/bin/perl
use strict;
use Data::Dumper;
my $x;
$x->{a}->{b}->{c}->{d} = 1;
print Dumper($x)
=begin output
$VAR1 = {
'a' => {
'b' => {
'c' => {
'd' => 1
}
}
}
};
=end output
#!/usr/bin/env python
x = {}
x['a']['b']['c']['d'] = 1
#!/usr/bin/env python
import collections
import pprint
dict_factory = lambda: collections.defaultdict(dict_factory)
x = collections.defaultdict(dict_factory)
x['a']['b']['c']['d'] = 1
print x['a']['b']['c']['d']
print pprint.pformat(x) # looks a bit messy, but it gives you the idea
"""
Sample output (the addresses [in hexadecimal] will likely be different):
1
defaultdict(<function <lambda> at 0x7f733afa6230>, {'a': defaultdict(<function <lambda> at 0x7f733afa6230>, {'b': defaultdict(<function <lambda> at 0x7f733afa6230>, {'c': defaultdict(<function <lambda> at 0x7f733afa6230>, {'d': 1})})})})
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment