How to build a multidimensional dictionary

1

Being new to Python I've been attempting to come up with the code to build a multidimensional dict/array.

The input data consists of csv fields with the first line denoted by the '<' character. I need to key on "target" and "product" fields:

0: rev, 1: target name, 2: product name, 3: svn rev, 4: time/date <1,ram,KATMAI,7416,1373386517.0,2013-07-09 15:15:17 -0700>

0: region name, 1: start addr, 2: end addr, 3: etc. LOAD_REGION2,0x0000004C,0x000003B4,92.6,7.4 LOAD_REGION2,0x0002152C,0x0001E6D4,47.7,52.3 LOAD_REGION2,0x0002EECC,0x00013034,28.8,71.2 <1,rom,KATMAI,7416,1373386517.0,2013-07-09 15:15:17 -0700> LOAD_REGION2,0x0000004C,0x000003B4,92.6,7.4 LOAD_REGION2,0x00005CEC,0x00039F14,90.9,9.1 LOAD_REGION2,0x00003A78,0x0003E488,94.5,5.5 <1,ram,TOASTER,7416,1373386517.0,2013-07-09 15:15:17 -0700> LOAD_REGION0,0x000000B8,0x00000348,82.0,18.0 LOAD_REGION0,0x0000AD10,0x00014EF0,65.9,34.1 LOAD_REGION1,0x00005244,0x00008CBC,63.1,36.9 LOAD_REGION3,0x00002A50,0x000FD5B0,99.0,1.0 LOAD_REGION3,0x000135B4,0x00000E4C,4.4,95.6 LOAD_REGION3,0x00000000,0x07B00000,100.0,0.0 <1,rom,TOASTER,7416,1373386517.0,2013-07-09 15:15:17 -0700> LOAD_REGION0,0x000000B8,0x00000348,82.0,18.0 LOAD_REGION0,0x00008710,0x000174F0,73.4,26.6 LOAD_REGION1,0x00003B6C,0x0000A394,73.4,26.6 LOAD_REGION3,0x00000208,0x000FFDF8,100.0,0.0 LOAD_REGION3,0x00000000,0x00014400,100.0,0.0 LOAD_REGION3,0x00000000,0x07B00000,100.0,0.0

I want to read each record and build an array with the major index of the target field and the minor index the product field. [target name][product name]["1"] = 7416,1373386517.0,2013-07-09 15:15:17 -0700 [target name][product name]["2"][region name] = 0x0000004C,0x000003B4,92.6,7.4

What would be correct way to build the dictionary? Or should I be using a multidimensional list array?

python
dictionary
asked on Stack Overflow Jul 31, 2013 by Ken Erickson

1 Answer

1

You can build a multidimensional dictionary by letting values of a dictionary be another dictionary. For example, you could have a dictionary that you can access like this:

value = d["target K"]["product B"][1]

as:

d = {"target J":{"product A":{0:"example01"}, "product B":{1:"example02"}}, 
     "target K":{"product B":{1:"example03"}}}

Also, btw, I took the "1", etc, out of quotes, as integers will work as dictionary keys.

The main restriction on dictionaries is that the keys must be hashable, in particular, not be dictionaries, but here they keys are either strings or integers, so it will work.

answered on Stack Overflow Jul 31, 2013 by tom10

User contributions licensed under CC BY-SA 3.0