[英]Multilevel dictionary in python
I would like to create a perl style multilevel dict in python however I'm struggling to get this going. 我想在python中创建一个perl风格的多级字典,但是我正在努力做到这一点。
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. 此代码似乎适用于两个级别的
hash[row[0]][row[10]]
但不适用于3或4个级别。
Any help would be much appreciated, I'm new to python so I appologies if this is silly question. 任何帮助将不胜感激,我是python的新手,所以我很抱歉这是一个愚蠢的问题。 I can do it in perl but not in python.
我可以用perl来做,但是不能用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:
有一个简单的Python函数提供以下结构:
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: 例如,这是上面的
hash
变量的预设输出:
>>> 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
}
}
}
I am not familiar with pearl, but in python you need to initiate a dictionary before calling a specific entry. 我不熟悉Pearl,但是在python中,您需要在调用特定条目之前启动字典。 The way you are using defaultdict, you create a structure that is only two levels deep.
您使用defaultdict的方式创建的结构只有两层。
If you don't really need the defaultdict functionality, this is a not so elegant, but fast way to do what you want. 如果您真的不需要defaultdict功能,这不是一种优雅的方法,而是一种快速执行所需操作的方法。
import sys
import csv
import pprint
hash = {}
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]]={}
hash[row[0]][row[10]]={}
hash[row[0]][row[10]][row[5]]=1
count = count+1
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(hash)
I am not familiar with pprint either, but I hope it can handle this structure. 我也不熟悉pprint,但希望它能处理这种结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.