Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to initialize a dict of dicts in Python? [duplicate]

A lot of times in Perl, I'll do something like this:

$myhash{foo}{bar}{baz} = 1 

How would I translate this to Python? So far I have:

if not 'foo' in myhash:     myhash['foo'] = {} if not 'bar' in myhash['foo']:     myhash['foo']['bar'] = {} myhash['foo']['bar']['baz'] = 1 

Is there a better way?

like image 651
mike Avatar asked Mar 16 '09 19:03

mike


People also ask

What is the correct way to copy a dictionary in Python?

Python Dictionary copy() The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.

How do you initialize a dictionary in Python?

Another way to initialize a python dictionary is to use its built-in “dict()” function in the code. So, you have to declare a variable and assign it the “dict()” function as an input value. After this, the same print function is here to print out the initialized dictionary.

Can we create dict with duplicate keys?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

How do I copy a key value pair to another dictionary in Python?

By using dict. copy() method we can copies the key-value in a original dictionary to another new dictionary and it will return a shallow copy of the given dictionary and it also helps the user to copy each and every element from the original dictionary.


1 Answers

If the amount of nesting you need is fixed, collections.defaultdict is wonderful.

e.g. nesting two deep:

myhash = collections.defaultdict(dict) myhash[1][2] = 3 myhash[1][3] = 13 myhash[2][4] = 9 

If you want to go another level of nesting, you'll need to do something like:

myhash = collections.defaultdict(lambda : collections.defaultdict(dict)) myhash[1][2][3] = 4 myhash[1][3][3] = 5 myhash[1][2]['test'] = 6 

edit: MizardX points out that we can get full genericity with a simple function:

import collections def makehash():     return collections.defaultdict(makehash) 

Now we can do:

myhash = makehash() myhash[1][2] = 4 myhash[1][3] = 8 myhash[2][5][8] = 17 # etc 
like image 123
John Fouhy Avatar answered Sep 20 '22 18:09

John Fouhy