python多级字典_Python中的多级字典

I would like to create a perl style multilevel dict in python however I'm struggling to get this going.

This is what I have tried:

import sys

import csv

import pprint

from collections import defaultdict

hash = defaultdict(dict)

FILE = csv.reader(open('dosageMP.txt', 'rU'), delimiter='\t')

FILE.next()

count = 0

for row in FILE:

if count < 10:

print row

hash[row[0]][row[10]][row[5]] = 1

count = count+1

pp = pprint.PrettyPrinter(indent=4)

pp.pprint(hash)

This code seems to work well for two level hash[row[0]][row[10]] but won't work for 3 or 4 levels.

Any help would be much appreciated, I'm new to python so I appologies if this is silly question. I can do it in perl but not in python.

The output i would like is :

Center->ROOM1->EXAM1

->EXAM2

ROOM2->EXAM1

->EXAM2

->EXAM3

Center2->ROOM3->EXAM1

解决方案

You're actually looking for a tree structure. There's a simply Python function that provides this structure:

from collections import defaultdict

def tree():

return defaultdict(tree)

Now you can set it as follows:

hash = tree()

hash['Center']['ROOM1']['EXAM1'] = 1

hash['Center']['ROOM1']['EXAM2'] = 2

hash['Center']['ROOM2']['EXAM1'] = 3

hash['Center']['ROOM2']['EXAM2'] = 4

hash['Center']['ROOM2']['EXAM3'] = 5

hash['Center2']['ROOM3']['EXAM1'] = 6

You can convert these back to dicts using:

def dicts(tree):

return {key: (dicts(tree[key]) if hasattr(tree[key], 'items') else tree[key]) for key in tree}

For example, here's a prettified output for the hash variable above:

>>> import json

>>> print json.dumps(dicts(hash), indent=4)

{

"Center2": {

"ROOM3": {

"EXAM1": 6

}

},

"Center": {

"ROOM2": {

"EXAM2": 4,

"EXAM3": 5,

"EXAM1": 3

},

"ROOM1": {

"EXAM2": 2,

"EXAM1": 1

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值