Reputation:
take a look at the following database.txt file:
donald
duck
123456
[email protected]
--------------------
suzy
giraffe
78910
[email protected]
--------------------
i need to take that file create a 2D dictionary that looks like this:
dict = {
'donald': {'fname': donald, 'lname': duck, 'phone': 123456, 'email': [email protected]}
'suzy': {'fname': suzy, 'lname': giraffe, 'phone': 78910, 'email': [email protected]}
}
the program should take the first name and create a key with it, and then take everything else, including the first name again, and create a second dictionary with other keys as an element to the key. when it reaches the "--------------------" it should restart this process. the goal is to be able to use the dictionary as such:
dict['donald']['phone'] = 123456
dict['suzy']['email'] = [email protected]
i have this so far, i am taking everything from the file and placing it in an list after i remove the linebreak from the string.
fhandle = open(input("Enter the database filename: "), "r")
lines = []
with fhandle as insert:
for line in insert:
cleaned_line = line.replace("\n", "")
lines.append(cleaned_line)
any ideas??
Upvotes: 2
Views: 552
Reputation: 1808
with dict comprehension:
keys = ['fname', 'lname', 'phone', 'email']
with open('database.txt', 'r') as stream:
a = stream.read().split('--------------------\n')
print({i.split('\n')[0]: dict(zip(keys, i.split('\n'))) for i in a})
output:
{
"suzy": {
"email": "[email protected]",
"fname": "suzy",
"lname": "giraffe",
"phone": "78910"
},
"donald": {
"email": "[email protected]",
"fname": "donald",
"lname": "duck",
"phone": "123456"
}
}
Upvotes: 1
Reputation: 4021
You can do it with common string operations (split()
, strip()
, etc.):
with open('database.txt', 'r') as f:
results = dict()
for line in f.read().strip().split('--------------------'):
if line.strip() != "":
first_name, last_name, phone, email = line.strip().split('\n')
results[first_name] = dict(first_name=first_name, last_name=last_name, phone=phone, email=email)
print results
Other way of doing exactly the same but with list and dict comprehensions
:
with open('database.txt', 'r') as f:
results = {first_name:dict(first_name=first_name, last_name=last_name, phone=phone, email=email) for first_name, last_name, phone, email in [line.strip().split('\n') for line in f.read().split('--------------------') if line.strip() != ""]}
print results
Output is the same for both cases:
{
'donald': {
'phone': '123456',
'first_name': 'donald',
'last_name': 'duck',
'email': '[email protected]'
},
'suzy': {
'phone': '78910',
'first_name': 'suzy',
'last_name': 'giraffe',
'email': '[email protected]'
}
}
Upvotes: 1
Reputation: 1390
As a quick solution I would do something like:
def parse_dict(name, lname, phone, email):
return (name, {"lname": lname, "phone": phone, "email": email})
with open("test.data") as f:
line_list = f.readlines()
data = {}
entry = []
for line in line_list:
if not line.startswith("---"):
entry.append(line.strip())
else:
# Send to process:
name, record = parse_dict(*entry)
data[name] = record
# Reset entry:
entry = []
print data, "\n"
print data["donald"], "\n"
print data["donald"]["email"], "\n"
Output:
{'donald': {'lname': 'duck', 'phone': '123456', 'email': '[email protected]'}, 'suzy': {'lname': 'giraffe', 'phone': '78910', 'email': '[email protected]'}}
{'lname': 'duck', 'phone': '123456', 'email': '[email protected]'}
[email protected]
Upvotes: 1