【问题标题】:Accessing nested values in nested dictionaries in Python 3.3在 Python 3.3 中访问嵌套字典中的嵌套值
【发布时间】:2013-09-29 18:01:12
【问题描述】:

我正在使用 Python 3.3 编写代码。

我有一组嵌套字典(如下所示),我尝试使用最低级别的键进行搜索并返回对应于第二级的每个值。

Patients = {}
Patients['PatA'] = {'c101':'AT', 'c367':'CA', 'c542':'GA'}
Patients['PatB'] = {'c101':'AC', 'c367':'CA', 'c573':'GA'}
Patients['PatC'] = {'c101':'AT', 'c367':'CA', 'c581':'GA'}

我正在尝试使用一组“for 循环”来搜索并提取附加到每个 Pat* 字典中的 c101 键的值,该字典嵌套在主患者字典下。

这是我目前所拥有的:

pat = 'PatA'
mutations = Patients[pat]

for Pat in Patients.keys(): #iterate over the Pat* dictionaries
    for mut in Pat.keys(): #iterate over the keys in the Pat* dictionaries
        if mut == 'c101': #when the key in a Pat* dictionary matches 'c101'
            print(mut.values()) #print the value attached to the 'c101' key

我收到以下错误,表明我的 for 循环将每个值作为字符串返回,并且不能将其用作字典键来提取值。

回溯(最近一次通话最后一次):
文件“文件名”,第 13 行,在
对于 Pat.keys() 中的 mut: AttributeError: 'str' 对象没有属性 'keys'

我认为我缺少与字典类有关的一些明显的东西,但我不能完全说出它是什么。我看过this question,但我认为这不是我要问的。

任何建议将不胜感激。

【问题讨论】:

    标签: for-loop dictionary python-3.x nested


    【解决方案1】:

    Patients.keys() 为您提供患者字典 (['PatA', 'PatC', 'PatB']) 中的键列表,而不是值列表,因此会出现错误。您可以使用dict.items 来迭代 key: value 对,如下所示:

    for patient, mutations in Patients.items():
        if 'c101' in mutations.keys():
             print(mutations['c101'])
    

    使您的代码正常工作:

    # Replace keys by value
    for Pat in Patients.values():
        # Iterate over keys from Pat dictionary
        for mut in Pat.keys():
            if mut == 'c101':
                # Take value of Pat dictionary using
                # 'c101' as a key
                print(Pat['c101'])
    

    如果您愿意,您可以在简单的单行中创建突变列表:

    [mutations['c101'] for p, mutations in Patients.items() if mutations.get('c101')]
    

    【讨论】:

    • 谢谢你,完全按照我的意愿工作。澄清一下,“for”语句采用患者(键)和突变(患者键的值)。然后 'if' 搜索突变作为键以提取值。
    【解决方案2】:
    Patients = {}
    Patients['PatA'] = {'c101':'AT', 'c367':'CA', 'c542':'GA'}
    Patients['PatB'] = {'c101':'AC', 'c367':'CA', 'c573':'GA'}
    Patients['PatC'] = {'c101':'AT', 'c367':'CA', 'c581':'GA'}
    
    for keys,values in Patients.iteritems():
       # print keys,values
        for keys1,values1 in values.iteritems():
                if keys1 is 'c101':
                    print keys1,values1
                    #print values1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2015-08-29
      相关资源
      最近更新 更多