Text file to dictionary with formatting the text
Question:
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)
Answers:
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']
})
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)
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']
})