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?
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.
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.
The straight answer is NO. You can not have duplicate keys in a 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With