簡體   English   中英

嵌套在字典中的列表

[英]Lists nested inside dictionary

因此,我正在嘗試開發一種方法來在字典中存儲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'}}

您可以將列存儲為元組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM