1

I have a program in Perl that I want to translate into Python. Right now the focus is on rote translation, then I will go through and make it more Pythonic (there are a lot of files and a couple people working on it so I don't want to mess up the logic flow by changing the code too much). The Perl code creates a hash InputData that it fills with data from an input file. At first it was 1-dimensional, so I just used a dictionary. Then the code added a second dimension, and after looking at this thread I used defaultdict(dict). Now my Perl code has added a third dimension and looking forward in the code there is a fourth dimension used as well.

I have been testing dicts in Jupyter Notebook, and I get this KeyError when I try to add a third dimension.

my_dict = defaultdict(dict)
my_dict['Status'] = 'free'
my_dict['Results']['Test1'] = 1
my_dict['Variables']['Coords']['X'] = 2

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-19-dbbf5ada990b> in <module>
      2 my_dict['Status'] = 'free'
      3 my_dict['Results']['Test1'] = 1
----> 4 my_dict['Variables']['Coords']['X'] = 2

KeyError: 'Coords'

Is there some other way to create a multidimensional Python dict? Is this ridiculous? What other data type could I use instead?

Thanks for any help!

kierabeth
  • 98
  • 1
  • 7

1 Answers1

0

You need to define my_dict['Variables']['Coords'] as a dictionary too, if you want to use it as such, perhaps by doing defaultdict(dict)

#Define as default dict
my_dict['Variables']['Coords'] = defaultdict(dict)
my_dict['Variables']['Coords']['X'] = 2

print(my_dict)

The output will be

defaultdict( <class 'dict'> , {
    'Status': 'free',
    'Results': {
        'Test1': 1
    },
    'Variables': {
        'Coords': defaultdict( <class 'dict'> , {
            'X': 2
        })
    }
})
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40