Python中的多个级别的键和值

Jus*_*rey 7 python dictionary python-2.7

我想知道我试图在python中实现的功能是否可行.

我有一个名为Creatures的全局哈希.生物包含称为哺乳动物,两栖动物,鸟类,昆虫的亚哈希.

哺乳动物有亚哈斯,称为鲸鱼,大象.两栖动物有子哈希,称为青蛙,幼虫.鸟类有亚哈希,叫鹰,长尾小鹦鹉.昆虫有子哈希,称为蜻蜓,蚊子.

再次,老鹰有子哈希,称为男性,女性.

我正在计算文本文件中所有这些生物的频率.例如,如果文件格式如下:

Birds   Eagle  Female
Mammals whales Male
Birds   Eagle  Female

I should output Creatures[Birds[Eagle[Female]]] = 2
                Creatures[mammals[Whales[Male]]] = 1  
Run Code Online (Sandbox Code Playgroud)

在Python中有可能吗?怎么做到呢?我是Python的新手,非常感谢帮助.我对字典只有1级,即键 - >值感到满意.但在这里,有多个键和多个值.我不知道如何处理这个问题.我正在使用python 2.6.谢谢你的推荐!

che*_*ner 24

分配给字典中的键的值本身可以是另一个字典

creatures = dict()
creatures['birds'] = dict()
creatures['birds']['eagle'] = dict()
creatures['birds']['eagle']['female'] = 0
creatures['birds']['eagle']['female'] += 1
Run Code Online (Sandbox Code Playgroud)

但是,您需要显式创建每个字典.与Perl不同,当您尝试处理未分配键的值时,Python不会自动创建字典.

当然,除非您使用defaultdict:

from collections import defaultdict
creatures = defaultdict( lambda: defaultdict(lambda: defaultdict( int )))
creatures['birds']['eagle']['female'] += 1
Run Code Online (Sandbox Code Playgroud)

对于任意级别的嵌套,您可以使用此递归定义

dd = defaultdict( lambda: dd )
creatures = dd
creatures['birds']['eagle']['female'] = 0
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您需要显式初始化整数值,否则creatures['birds']['eagle']['female']将假定值为另一个值defaultdict.


Syl*_*oux 2

如果您只需要“计算”事物 - 并假设数据文件包含所有所需级别的“散列” - 这就能解决问题:

import collections

result = collections.defaultdict(int)

with open("beast","rt") as f:
    for line in f:
        hashes = line.split()
        key = '-'.join(hashes)
        result[key] += 1

print result
Run Code Online (Sandbox Code Playgroud)

产生结果:
defaultdict(<type 'int'>, {'Mammals-whales-Male': 1, 'Birds-Eagle-Female': 2})

如果您需要嵌套字典 - 仍然可以对该结果进行后处理......