Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Text file to dictionary with formatting the text

I’m struggling to create the dictionary out of txt file which contains following:

20
Robert  Jack                   
Robert  Gary
Lizzie  Dave
Lena
Mia     Dave
Mia     Caroline
Rafael
Robert  Nick
Daniela Jack
Danny   Merry
Danny   Joel
Adam    Robert
Adam    Mia
Chris   Mario
Chris   June
Chris   Joel
Joel    Benny
Wayne   Jack

Social network showing list of people and their friends, I have to change the data into dictionary and present people with their friends next to them as follows: Robert -> Gary, Jack etc.

with open('nw_data1.txt', 'r') as f: 
    lines = f.readlines() 
            file_dict = {} 


    for line in lines: 

        key, value = line.split('-', '>') 
        key = key.strip() 
        value = value.strip() 
        file_dict[key] = value 

        print(file_dict) 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would use a collections.defaultdict to solve this.

from collections import defaultdict

with open('nw_data1.txt', 'r') as f: 
    lines = f.readlines() 

network = defaultdict(list)

for line in lines:
    name, *friends = line.split()
    network[name] += friends

With network now being:

defaultdict(<class 'list'>, {
  'Robert': ['Jack', 'Gary', 'Nick'], 
  'Lizzie': ['Dave'], 
  'Lena': [],   
  'Mia': ['Dave', 'Caroline'], 
  'Rafael': [], 
  'Daniela': ['Jack'], 
  'Danny': ['Merry', 'Joel'], 
  'Adam': ['Robert', 'Mia'], 
  'Chris': ['Mario', 'June', 'Joel'], 
  'Joel': ['Benny'], 
  'Wayne': ['Jack']
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading