0

私はPython 3.3で書いています。

ネストされた辞書のセット (以下を参照) があり、最下位レベルのキーを使用して検索し、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 ループ」のセットを使用して、メインの Patients 辞書の下にネストされた各 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 ループが各値を文字列として返し、これをディクショナリ キーとして使用して値を引き出すことができないことを示唆しています。

トレースバック (最新の呼び出しが最後):
ファイル "filename"、13 行
目、pat.keys() の mut の場合: AttributeError: 'str' オブジェクトに属性 'keys' がありません

辞書クラスに関係する明らかな何かが欠けていると思いますが、それが何であるかはよくわかりません。私はこの質問に目を通しましたが、私が求めていることはまったくないと思います。

アドバイスをいただければ幸いです。

4

2 に答える 2

2

Patients.keys()値のリストではなく、患者辞書のキーのリスト(['PatA', 'PatC', 'PatB'])を提供するため、エラーが発生します。dict.items次のようにキーと値のペアを反復処理するために使用できます。

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')]
于 2013-09-24T13:32:58.457 に答える
0
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
于 2016-09-27T14:19:25.833 に答える