假設以下文本檔案 (dict.txt) 具有
1 2 3
aaa bbb ccc
字典應該是{1: aaa, 2: bbb, 3: ccc}這樣的
我做了:
d = {}
with open("dict.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
print (d)
但它沒有用。我認為這是因為txt檔案的結構。
uj5u.com熱心網友回復:
你想作為鍵的資料在第一行,你想作為值的所有資料在第二行。
所以,做這樣的事情:
with open(r"dict.txt") as f: data = f.readlines() # Read 'list' of all lines
keys = list(map(int, data[0].split())) # Data from first line
values = data[1].split() # Data from second line
d = dict(zip(keys, values)) # Zip them and make dictionary
print(d) # {1: 'aaa', 2: 'bbb', 3: 'ccc'}
uj5u.com熱心網友回復:
根據 OP 編輯??更新答案:
#Initialize dict
d = {}
#Read in file by newline splits & ignore blank lines
fobj = open("dict.txt","r")
lines = fobj.read().split("\n")
lines = [l for l in line if not l.strip() == ""]
fobj.close()
#Get first line (keys)
key_list = lines[0].split()
#Convert keys to integers
key_list = list(map(int,key_list))
#Get second line (values)
val_list = lines[1].split()
#Store in dict going through zipped lists
for k,v in zip(key_list,val_list):
d[k] = v
uj5u.com熱心網友回復:
首先為鍵和值創建單獨的串列,條件如下:
if (idx % 2) == 0:
keys = line.split()
values = lines[idx 1].split()
然后合并兩個串列
d = {}
# Get all lines in list
with open("dict.txt") as f:
lines = f.readlines()
for idx, line in enumerate(lines):
if (idx % 2) == 0:
# Get the key list
keys = line.split()
# Get the value list
values = lines[idx 1].split()
# Combine both the lists in dictionary
d.update({ keys[i] : values[i] for i in range(len(keys))})
print (d)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/400149.html
下一篇:將帶有負數和正數的串列拆分為字典
