2017-10-14 23 views
2

我有這樣的程序:如何在列表中創建字典數據?

def file(fname): 
    lines = open(fname).read().splitlines() 
    return(lines) 
print(file('venue.txt')) 

而且它出來像這樣,我變成名單:

['room 1, 10, 250'] 

如何構建一個字典數據與它,以便它可以是這樣的:

[{'name': 'room 1', 'max': 10, 'cost': 250}] 

一些線索也許對我來說是建立它。 感謝

編輯:

def file(fname): 
    lines = open(fname).read().splitlines() 
    new = [] 
    for i in lines: 
     split = i.split(', ') 
     new.append({'name':split[0],'max':split[1],'cost':split[2]}) 
    return(new) 
print(file('venue.txt')) 

它打印:

new.append({'name':split[0],'max':split[1],'cost':split[2]}) 
IndexError: list index out of range 

是什麼意思?

回答

1

你可以試試這個:

import re 
def file(fname): 
    lines = open(fname).read().splitlines() 
    return(lines) 
headers = ["name", "max", "cost"] 
data1 = [re.split(",\s+", i) for i in file("venue.txt")] 
final_data = [{a:b for a, b in zip(headers, data} for data in data1] 
print(final_data) 
+0

什麼都沒有出來 –

+0

@Joehan你必須打印'final_data'。請參閱我最近的編輯。 – Ajax1234

+0

yes..it works ..謝謝...但它只打印一個數據...如果它不止一個......怎麼樣data = re.split(「,\ s +」,file(「 .txt「)[0])...我將值0更改爲其他數字它也打印其他數據...我如何獲得所有數據打印在一次?...謝謝...抱歉如果我問了很多@ Ajax1234 –

1

如果他們被', '分開,您可以使用', '上的split()。 將返回一個包含分隔項目的數組。

對於示例:

current_list = ['room 1, 10, 250'] 
split = current_list[0].split(', ') 
new_list = [{'name': split[0], 'max': int(split[1]), 'cost': int(split[2])}] 
print(new_list) 

輸出:

[{'name': 'room 1', 'max': 10, 'cost': 250}] 

對於較大的列表:

current_list = ['room 1, 10, 250', 'room 2, 30, 500','room 3, 50, 850'] 
new_list = [] 
for i in current_list: 
    split = i.split(', ') 
    new_list.append({'name': split[0], 'max': int(split[1]), 'cost': int(split[2])}) 

print(new_list) 

輸出:

[{'name': 'room 1', 'max': 10, 'cost': 250}, {'name': 'room 2', 'max': 30, 'cost': 500}, {'name': 'room 3', 'max': 50, 'cost': 850}] 
+1

使用'INT(分割[1])'和'INT(分割[2])'轉換那些爲整數。 – smarx