[英]Loop prints multiple lines (as intended) but only writes one line to the file
[英]File to dictionary only prints one
我有一個文本文件,內容如下:
a;b
a;c
a;d
b;h
c;e
e;f
e;g
e;j
f;b
g;d
h;b
h;e
i;d
i;e
但是當我把它做成字典后打印出來時
def read_graph(file_name):
graph = {}
for line in open(file_name):
if ";" in line:
key, val = map(str.strip, line.split(";"))
graph[key] = val
return dict(sorted(graph.items())))
它打印:
{'a': 'b', 'b': 'd', 'c': 'e', 'd': 'g', 'e': 'd', 'f': 'd'}
我如何使它打印重復的鍵?
我假設為此您希望使用字符串列表而不是單個字符串作為值,否則您的字典將繼續替換同一鍵的值。
代替:
{'a': 'b'}
您可能需要一個結構,例如:
{'a': ['b','c','d']}
使用您的 function:
def read_graph(file_name):
graph = {}
for line in open(file_name):
if ";" not in line: continue
key, val = line.strip().split(';')
if key not in graph: graph[key] = list()
if val not in graph[key]: graph[key].append(val)
return dict(sorted(graph.items()))
read_graph('file.txt')
{'a': ['b', 'c', 'd'], 'c': ['e'], 'b': ['h'], 'e': ['f', 'g', 'j'], 'g': ['d'], 'f': ['b'], 'i': ['d', 'e'], 'h': ['b', 'e']}
python(以及我知道的所有其他語言)中的字典對每個鍵都有唯一的值,並且當您為現有鍵輸入新值時會覆蓋它們。
考慮一種不同類型的數據結構,例如一組元組,例如
{('a','b'), ('a','c'), ...}
或者,看起來你正在制作一個圖表,一個字典,其中值是頂點列表而不是單個頂點,例如
{'a':['b','c'],...}
要制作一組元組,請替換該行
graph[key] = val
和
graph.append((key, val))
要制作字典到列表,請使用
if key in graph:
graph[key].append(val)
else:
graph[key] = [val]
希望這可以幫助!
你不能因為那是一個字典,並且不允許有兩個相同的鍵,否則它會模棱兩可。 您可以按鍵分組。
def read_graph(file_name):
graph = {}
for line in open(file_name):
if ";" in line:
key, val = map(str.strip, line.split(";"))
if key not in graph:
graph[key] = [val]
else:
graph[key].append(val)
return dict(sorted(graph.items())))
所以現在每個鍵都有一個包含其值的數組。
由於您似乎正在使用圖形結構,因此我建議您查看NetworkX package 的 Python。 他們有預先構建的圖形數據結構供您使用,還有許多可以在它們上運行的算法。
import networkx as nx
graph = nx.Graph()
with open(file_name) as f: # This closes the file automatically when you're done
for line in f:
if ";" in line:
source, dest = map(str.strip, line.split(";"))
graph.add_edge(source, dest)
如果您仍想僅使用香草 Python:
Python 的字典每個鍵只能有一個值。 要為單個鍵存儲多個值,您必須將鍵存儲在值列表中。
my_dict = {
'a': ['b', 'c', 'd'],
'b': ['h'],
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.