Python Forum
Dictionary multi dimension support - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Dictionary multi dimension support (/thread-12213.html)



Dictionary multi dimension support - sripylearn - Aug-14-2018

Need Help on below error

When i write a code like below
dic1 = {}
dic1['key1']['key2']  = 'Value1'

print(dic1)
Below error is encountered
Traceback (most recent call last):
File "C:/v586150-Prsnl/learning/python/Vz450inP/kirandic.py", line 3, in <module>
dic1['key1']['key2'] = 'Value1'
KeyError: 'key1'

I am forced to define a subkey definition before assignment. Is there a better approach that Python understand the definition of the type and auto instantiate like Perl
dic1 = {}
dic1['key1'] = {}
dic1['key1']['key2']  = 'Value1'

print(dic1)
Process finished with exit code 1


RE: Dictionary multi dimension support - Vysero - Aug-14-2018

I am not 100% sure why you would attempt to instantiate your dictonary like you have. Normally, if I were trying to do something like that I would say:

dict = {'key1': 'Value1', 'key2': 'Value2'}
print(dict)
Output:
Output:
{'key1': 'Value1', 'key2': 'Value2'}
If I wanted a nested dictionary I would say:

dict_outer = {}

dict_outer['dict1'] = {}

dict_outer['dict1']['dict1_key'] = 'value'

print(dict_outer)
Output:

Output:
{'dict1': {'dict1_key': 'value'}}



RE: Dictionary multi dimension support - Larz60+ - Aug-14-2018

Quote:I am forced to define a subkey definition before assignment.
That is what you must do, but note that once nodes are created, you can add to them
example:
>>> dict1 = {
...     'key1': {
...         'key2': 'Value1'
...     }
... }
>>> dict1['key1']['Desc'] = 'No desc'
>>> dict1['newkey'] = {}
>>> dict1
{'key1': {'key2': 'Value1', 'Desc': 'No desc'}, 'newkey': {}}



RE: Dictionary multi dimension support - buran - Aug-14-2018

you can use dict.setdefault() method
d = {}
d.setdefault('key1', {})['key2'] = 'foo'
print(d)
d.setdefault('key1', {})['key3'] = 'bar'
print(d)
Output:
{'key1': {'key2': 'foo'}} {'key1': {'key3': 'bar', 'key2': 'foo'}}
another option is to use defaultdict from collections

from collections import defaultdict
d = defaultdict(dict)
d['key1']['key2'] = 'foo'
print(d)
d['key1']['key3'] = 'bar'
print(d)
Output:
defaultdict(<class 'dict'>, {'key1': {'key2': 'foo'}}) defaultdict(<class 'dict'>, {'key1': {'key2': 'foo', 'key3': 'bar'}})