python - 如何在Python中创建和打印多级字典?

标签 python

所需数据结构:

Name -->gene1
             --> CDS
                     1   3
                     6   10
             --> exon
                     4   8
       ->gene2
             --> CDS
                     4   9

我正在尝试使用 python 字典创建并打印上述数据结构。我对 Python 非常陌生,这就是为什么我无法创建它。需要帮助来创建它。

尝试:

dict = {'name' :{'gene1': {'CDS' : [1, 3]}}}
for name in dict:
        print name
        for gene in dict[name]:
                print "\t" +gene
                for feature in dict[name][gene]:
                        print "\t\t"+feature
                        print "\t\t\t",
                        print dict[name][gene][feature]

输出:

name
        gene1
                CDS
                        [1, 3]

最佳答案

dct = {"gene1": {"CDS": [[1, 3], [6, 10]], "exon": [[4, 8]]}, "gene2": {"CDS": [[4, 9]]}}

for outer_key, outer_value in dct.items():
    print(outer_key)
    for inner_key, inner_value in outer_value.items():
        print("\t", inner_key)
        for elem in inner_value:
            print("\t\t", elem)

你的问题很不清楚,但这里有一个可能的解决方案。

python2中的

items()iteritems()

这将输出:

gene2
         CDS
                 [4, 9]
gene1
         CDS
                 [1, 3]
                 [6, 10]
         exon
                 [4, 8]

gene1 gene2 是外部字典中的键,CDSexon 是内部字典(值外部字典的),它们的值是列表(嵌套列表)

关于python - 如何在Python中创建和打印多级字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41262348/

相关文章:

python - 如何才能使 FFT 峰值精确地处于信号频率?

python - "conversion from method to Decimal is not supported django"错误

python - 没有名为 'google.cloud' Dockerfile python 的模块

python - 使用 python 更改文件权限的 Chmod 问题

python - ndb 单例模式

python - 要使用 python pandas 在一个数据帧中查找另一个数据帧 id 的平均值?

python - Django/Python 中是否有工具可以查看子类及其从多个父类继承的所有属性和方法?

python - 在 Python 中反转字符串的 "group"

python - 多维数组到字典

python - 如何使用python将稀疏矩阵转换为密集形式