2017-11-02 5 views
0

그래서 각 사전의 키/값에 액세스 할 수 있도록 사전 내에 4 가지 카테고리 (A, B, C, D)를 저장할 수있는 방법을 개발하려고합니다. 파일 이름과 대조하여 확인하십시오. 지금까지이 카테고리 중 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

탭 분리 파일을위한'csv' 모듈. – Daniel

+0

입력 파일의 'Component1'값이 '1'인 두 행이 있습니다. 이것이 생길 때 당신은 무엇을하고 싶니? 어떤 ** ** 사전을보아야합니까 (현재 코드가 출력하는 것을 실제로 신경 쓰지 않아야합니까?)? – 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

튜플 내의 값에 얼마나 쉽게 액세스 할 수 있습니까? 또한 단일 기증자에 대해 여러 데이터가있는 경우 어떻게해야합니까? 특정 사전 키에 대해 두 개의 튜플이 있을까요? – superasiantomtom95

+0

튜플 항목은 색인으로 액세스 할 수 있으며 기증자 당 여러 항목에 대해서는 defaultdict 목록이 있습니다. – Daniel