Search code examples
pythonlistdictionarytext-filessorteddictionary

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?


Solution

  • 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:

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