Python中的多级字典 [英] Multilevel dictionary in python

查看:1562
本文介绍了Python中的多级字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中创建一个perl样式的多级字典,但是我正在努力做到这一点。



这是我试过的:

 导入sys 
导入csv
导入pprint $ b $ from集合import defaultdict

)hash = defaultdict(dict)
FILE = csv.reader(open('dosageMP.txt','rU'),delimiter ='\t')
FILE.next()
count = 0
用于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)

代码对于两级散列[row [0]] [row [10]] 似乎工作得很好,但不适用于3或4级。



任何帮助将不胜感激,我是python新手,所以我appologies如果这是愚蠢的问题。我可以在perl中完成,但不能在python中完成。



我想输出的结果是:

pre > Center-> ROOM1-> EXAM1
- > EXAM2
ROOM2-> EXAM1
- > EXAM2
- > EXAM3
Center2-> ROOM3-> EXAM1


解决方案

你实际上正在寻找一个树结构。有一个简单的Python函数,它提供了这种结构:

  from集合import defaultdict 
def tree():
return defaultdict(tree)

现在你可以如下设置:

pre $ hash $ tree )
hash ['Center'] ['ROOM1'] ['EXAM1'] = 1
hash ['Center'] ['ROOM1'] ['EXAM2'] = 2
hash ['Center'] ['ROOM2'] ['EXAM1'] = 3
hash ['Center'] ['ROOM2'] ['EXAM2'] = 4 $ b $ hash ['Center'] [ 'ROOM2'] ['EXAM3'] = 5
hash ['Center2'] ['ROOM3'] ['EXAM1'] = 6

您可以使用以下命令将它们转换为字典:

  def dicts(tree) :
return {key:(dicts(tree [key])如果hasattr(tree [key],'items')else tree [key])对于树中的键}

例如,下面是 ha的美化输出sh 上面的变量:

 >>> import json 
>>>打印json.dumps(dicts(hash),indent = 4)
{
Center2:{
ROOM3:{
EXAM1:6
}
Center:{
ROOM2:{
EXAM2:4,
EXAM3:5,
EXAM1:3
},
ROOM1:{
EXAM2:2,
EXAM1:1
}
}
}


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
        }
    }
}

这篇关于Python中的多级字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆