[英]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.