這是原始文本檔案:
s1 10 s2
s2 12 s3
s3 25 s1
s1 14 s3
我正在制作每行中第一個值的字典作為鍵,輸出應該是: {'s1': [ ('s2', 's10'), ('s3', '14') ], 's2' : [('s3', '12')], 's3': [('s1', '25')]}
當我運行我的代碼時,我得到一個關鍵錯誤:
def graph_dict(filename):
dictx = {}
with open(filename) as x:
for i in x:
c, c1, c2 = i.split()
dictx[c] = [(c2,c1)]
return dictx
Traceback (most recent call last):
File "<pyshell#361>", line 1, in <module>
graph_dict("filename.txt")
File "*********************************************", line 7, in graph_dict
dictx[c] = [(c2,c1)]
KeyError: 's1'
在上面的行中,當我進入 dictx[c] = [(c2,c1)] 我得到輸出;
{'s1': [('s3', '14')], 's2': [('s3', '12')], 's3': [('s1', '25')]}
因此,它在嘗試將 2 個元組的串列添加到“s1”時拋出了一個關鍵錯誤,我認為這應該沒問題。有沒有人建議獲得輸出:
{'s1': [('s2', 's10'), ('s3', '14')], 's2': [('s3', '12')], 's3': [('s1', '25')]}
謝謝
uj5u.com熱心網友回復:
除了 using defaultdict,您還可以嘗試捕獲該例外(稱為It's Easier To Ask Forgiveness Than To Get Permission):
def graph_dict(filename):
dictx = {}
with open(filename) as x:
for i in x:
c, c1, c2 = i.split()
try:
dictx[c] = [(c2,c1)]
except KeyError:
dictx[c] = [(c2, c1)]
return dictx
uj5u.com熱心網友回復:
dictx[c] = [(c2,c1)]假設c字典中已經存在。你可以改為測驗。使用 .append 會快一點。
def graph_dict(filename):
dictx = {}
with open(filename) as x:
for i in x:
c, c1, c2 = i.split()
if c in dictx:
dictx[c].append((c2,c1))
else:
dictx[c] = [(c2, c1)]
return dictx
uj5u.com熱心網友回復:
利用.setdefault()
def graph_dict(filename):
dictx = {}
with open(filename) as x:
for i in x:
c, c1, c2 = i.split()
dictx.setdefault(c,[]).append((c2,c1))
return dictx
print(graph_dict(r'c:\test\dat.txt'))
{'s1': [('s2', '10'), ('s3', '14')], 's2': [('s3', '12')], 's3': [('s1', '25')]}
uj5u.com熱心網友回復:
from collections import defaultdict
def graph_dict(filename):
dictx = defaultdict(list)
with open(filename) as x:
for i in x:
c, c1, c2 = i.split()
dictx[c] = [(c2,c1)]
return dictx
print(graph_dict('data'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528180.html
標籤:Python字典
上一篇:從嵌套字典中的現有對生成鍵:值對
下一篇:如何列印出字典中的所有其他鍵?
