2017-11-02 8 views
0

私は各辞書の中のキー/値にアクセスできるように、辞書内に4つの異なるカテゴリ(A、B、C、Dと呼ぶ)を格納する方法を開発しようとしています。ファイル名と照合してください。これまでのところ、3つのカテゴリのうち3つを辞書に格納できましたが、4番目のものは格納できませんでした。カテゴリはExcelファイルからのもので、通常の.txtファイル(.txtファイルを含む)にコピーされました。辞書に4番目のコンポーネントを追加する方法はありますか? .txtファイルネストされた内側の辞書をリストする

リンク:https://drive.google.com/file/d/0B2s43FKt5BZgQldULXVOR0RBeTg/view?usp=sharing

は、ここに私のスクリプトです:

from collections import defaultdict 
source_file = <file path>-<file name>.txt 
data_set = defaultdict(list) #sets up a defaultdict because there may be multiple overlapping keys 
s = [b for b in [i.strip('\n').split('\t') for i in open(source_file)] if b] # removes new line & tab spaces in .txt file 
for a, b, c, d in s: # a is donor, b is barcode, c is batch, d is donor 
    if a == 'Component1': # We don't want to save the column headings 
    pass 
    else: 
    data_set[a].append({b: c}) # creates the default dictionary 

出力は一瞬のように、このようなものです:

{'1':[{'ab':'tg'},{'dd':'dd'}],'2':{'dc':'yh'},3:{'we':'hh'}} 
+0

th e 'csv'-moduleをタブ区切りファイルとして使用します。 – Daniel

+0

あなたの入力ファイルは 'Component1'値が' 1'の2行です。これが起こったときに何が起こりたいですか? **どのような** **ディクショナリのように見える(本当にあなたの現在のコードの出力を気にしないでください)? – martineau

答えて

1

あなたはタプルとしてあなたの列を格納することができます:

import csv 
from collections import defaultdict 
source_file = "<file path>-<file name>.txt" 
data_set = defaultdict(list) 
with open(source_file) as f: 
    lines = csv.reader(f, delimiter='\t') 
    _ = next(lines) # skip header 
    for donor, barcode, batch, donor2 in lines: 
     data_set[a].append((barcode, batch, donor2)) # save columns as tuple 
+0

タプル内の値に簡単にアクセスできますか?また、単一のドナーに複数のデータがある場合はどうなりますか?特定の辞書キーに2つのタプルがあるでしょうか? – superasiantomtom95

+0

タプル項目はインデックスでアクセスでき、ドナーごとに複数のエントリーにはdefaultdictのリストがあります。 – Daniel

関連する問題