如何构建多维字典

时间:2013-07-31 01:24:14

标签: python dictionary

成为Python新手我一直试图想出构建多维dict /数组的代码。

输入数据由csv字段组成,第一行由'<'表示字符。我需要键入“目标”和“产品”字段:

0:rev,1:目标名称,2:产品名称,3:svn rev,4:时间/日期 < 1,ram,KATMAI,7416,1373386517.0,2013-07-09 15:15:17 -0700>

0:区域名称,1:启动地址,2:结束地址,3:等等 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

我想读取每条记录并使用目标字段的主索引构建一个数组,并将次要索引构建为产品字段。 [目标名称] [产品名称] [“1”] = 7416,1373386517.0,2013-07-09 15:15:17 -0700 [目标名称] [产品名称] [“2”] [地区名称] = 0x0000004C,0x000003B4,92.6,7.4

构建字典的正确方法是什么?或者我应该使用多维列表数组?

1 个答案:

答案 0 :(得分:1)

您可以通过让字典的成为另一个字典来构建多维字典。例如,您可以使用这样的字典:

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

为:

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

另外,顺便说一句,我从引号中取出“1”等,因为整数将作为字典键。

字典的主要限制是键必须是可清除的,特别是不是字典,但这里它们的键是字符串或整数,所以它可以工作。