【发布时间】: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