Python中的多个级别的键和值 [英] Multiple levels of keys and values in Python

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

问题描述

我想知道我想要在python中实现的功能是否可行。



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



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



再次,老鹰们的子哈希叫做男性,女性。



我计算所有这些来自文本文件的生物。例如,如果文件格式如下:

 鸟鹰女
哺乳动物鲸鱼男
鸟鹰女

我应该输出生物[鸟[鹰[女]]] = 2
生物[哺乳动物[鲸鱼[男]]] = 1

是否可能在Python中?怎么办?我对Python很新,请大家帮忙。我只喜欢字典只能达到1级,即键 - 值。但是在这里,有多个键和多个值。我不知道如何进行这个。我使用的是python 2.6。感谢在advace!

解决方案

如果你只需要计数的东西 - 假设数据文件包含所有必需的级别的哈希 - 这将是诀窍:

  import collections 

result = collections。 default dict(int)

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

打印结果

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



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


I wanted to know if the functionality i am trying to implement in python is possible.

I have a global hash called Creatures. Creatures contain sub-hashes called mammals, amphibians, birds, insects.

Mammals have sub-hashes called whales, elephants. Amphibians have sub-hashes called frogs, larvae. Birds have sub-hashes called Eagle, parakeet. Insects have sub-hashes called dragonfly, mosquito.

Again, Eagles have sub-hashes called male, female.

I am counting the frequencies of all these creatures from a text file. For example, if the file is in below format:

Birds   Eagle  Female
Mammals whales Male
Birds   Eagle  Female

I should output Creatures[Birds[Eagle[Female]]] = 2
                Creatures[mammals[Whales[Male]]] = 1  

Is it possible in Python? How can it be done? I am very new to Python and please help is much appreciated. I am comfortable with dictionaries only upto 1 level, i.e. key-> value. But here, there are multiple keys and multiple values. i am not sure how to proceed with this. I am using python 2.6. Thanks in advace!

解决方案

If you just have to "count" things -- and assuming the data file contains all the required level of "hashes" -- that will do the trick:

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

Producing the result:
defaultdict(<type 'int'>, {'Mammals-whales-Male': 1, 'Birds-Eagle-Female': 2})

If you require nested dictionary -- post-processing of that result is still possible...

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

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