【问题标题】:File to dictionary only prints one文件到字典只打印一个
【发布时间】:2019-10-04 23:28:49
【问题描述】:

我有一个文本文件,内容如下:

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'}

如何让它打印重复的键?

【问题讨论】:

标签: python list dictionary text-files sorteddictionary


【解决方案1】:

为此,我假设您希望使用字符串列表而不是单个字符串作为值,否则您的字典将不断替换同一键的值。

代替:

{'a': 'b'}

您可能需要这样的结构:

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

使用你的功能:

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']}

【讨论】:

    【解决方案2】:

    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]
    

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      你不能,因为那是一个字典,并且不允许有两个相同的键,否则会模棱两可。可以按键分组。

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

      所以现在每个键都有一个包含其值的数组。

      【讨论】:

        【解决方案4】:

        由于您似乎正在使用图形结构,我建议您查看 Python 的 NetworkX 包。他们预先构建了供您使用的图形数据结构以及许多可以对其进行操作的算法。

        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'],
            ...
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-15
          • 2020-06-18
          相关资源
          最近更新 更多