2017-01-24 46 views
-1

我想從文本文件創建一個字典。Python - 從文件中創建數組的字典

的文本文件:

***Comment line - not to be read by program*** 
jdoe | doe | John Doe | 0001 | True 
jsmith | smith | John Smith | 0002 | False 

字典將最好的樣子:

accounts = { 
'jdoe' : ['doe','John Doe', '0001', True], 
'jsmith' : ['smith', 'John Smith', '0002', False] 
} 

將需要此代碼是什麼工作?

+1

這將是一個簡單得多的[JSON](https://docs.python.org/3/library/json.html) – ti7

+0

歡迎StackOverflow上。請閱讀並遵守幫助文檔中的發佈準則。 [在主題](http://stackoverflow.com/help/on-topic)和[如何提問](http://stackoverflow.com/help/how-to-ask)適用於此處。 StackOverflow不是一個編碼或教程服務。 – Prune

+0

@ ti7爲什麼json會更簡單?許多程序讀寫csv的。我們對這些數據的來源一無所知,修改這些數據源可能非常困難。 json是一個序列化協議,不是邪教。 – tdelaney

回答

1

一個簡單的解決辦法是:

accounts={} 
with open("replacethiswithrealfilename") as f: 
    for line in f: 
     line=line.strip() 
     if line.startswith("***") or not line: 
      continue # ignore comments, ignore empty lines 
     sl=[s.strip() for s in line.split("|")] 
     sl[-1]=(sl[-1]=="True") 
     accounts[sl[0]]=sl[1:] 
0

我只是回答它,所以你有東西,但是,你應該閱讀一些Python編程書籍。

b = {} #your final dictionary 
a = "jdoe | doe | John Doe | 0001 | True" # for loop through the lines in a file, this is just one line 
a = a.split('|') #splits up your string into a list 
b[a[0]] = a[1:] # {'jdoe ': [' doe ', ' John Doe ', ' 0001 ', ' True']} 
1

事情是這樣的:

text_file_path = r'your_path' 

accounts = {} 
with open(text_file_path) as f: 
    for line in f.readlines()[1:]: 
     info = line.split(' | ') 
     if info: # possibly ignore blank line at end of file 
      key, values = info[0], info[1:] 
      values[-1] = values[-1] == 'True' 
      accounts[key] = values 

print(accounts) 
0

可以使用csv模塊讀取文件的元組的行和創建從字典那是可迭代的。複雜的因素是註釋行,但可以使用生成器在發佈者看到它們之前將其剝離。把它放在一起,你會得到

import csv 

def strip_comments(fp): 
    """iterate uncommented lines of a file""" 
    for line in fp: 
     if not line.startswith('***'): 
      yield line 

with open('test.csv', 'r', newline='') as in_file: 
    reader = csv.reader(strip_comments(in_file), delimiter="|", skipinitialspace=True) 
    accounts = {row[0]:row[1:] for row in reader}