简体   繁体   English

文件到字典只打印一个

[英]File to dictionary only prints one

I have a text file that reads:我有一个文本文件,内容如下:

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  

but when I print it after making it into a dictionary但是当我把它做成字典后打印出来时

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())))

It prints:它打印:

{'a': 'b', 'b': 'd', 'c': 'e', 'd': 'g', 'e': 'd', 'f': 'd'}

how do I make it where it prints the keys that repeat?我如何使它打印重复的键?

I assume for this you'd want to use a list of strings instead of a single string as the value, otherwise your dictionary will keep replacing the value for the same key.我假设为此您希望使用字符串列表而不是单个字符串作为值,否则您的字典将继续替换同一键的值。

Instead of:代替:

{'a': 'b'}

You would probably want a structure such as:您可能需要一个结构,例如:

{'a': ['b','c','d']}

Using your function:使用您的 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']}

Dictionaries in python (and every other language I know) have unique values for each key, and will overwrite them when you put a new value in for an existing key. python(以及我知道的所有其他语言)中的字典对每个键都有唯一的值,并且当您为现有键输入新值时会覆盖它们。

Consider a different kind of data structure, like a set of tuples, eg考虑一种不同类型的数据结构,例如一组元组,例如

{('a','b'), ('a','c'), ...}

Or, as it looks like you are making a graph, a dictionary where the values are lists of vertices instead of individual vertices, eg或者,看起来你正在制作一个图表,一个字典,其中值是顶点列表而不是单个顶点,例如

{'a':['b','c'],...}

To make the set of tuples, replace the line要制作一组元组,请替换该行

        graph[key] = val

with

graph.append((key, val))

To make a dictionary-to-lists, use要制作字典到列表,请使用

if key in graph:
    graph[key].append(val)
else:
    graph[key] = [val]

Hope this helps!希望这可以帮助!

You cannot because that is a dictionary, and it is not allowed to have two same keys or it would ambiguous.你不能因为那是一个字典,并且不允许有两个相同的键,否则它会模棱两可。 You could group by key.您可以按键分组。

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())))

So now you have for every key, an array with its values.所以现在每个键都有一个包含其值的数组。

Since you seem to be working with a graph structure, I would recommend you look at the NetworkX package for Python.由于您似乎正在使用图形结构,因此我建议您查看NetworkX package 的 Python。 They have pre-built graph data-structures for you to use and many algorithms that can operate on them.他们有预先构建的图形数据结构供您使用,还有许多可以在它们上运行的算法。

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)

In case you still want to use vanilla Python only:如果您仍想仅使用香草 Python:

Python's dictionaries can only have one value per key. Python 的字典每个键只能有一个值。 To store multiple values for a single key, you have to store your keys in a list of values.要为单个键存储多个值,您必须将键存储在值列表中。

my_dict = {
    'a': ['b', 'c', 'd'],
    'b': ['h'],
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM