看看下面的database.txt文件:
donald
duck
123456
donald@duck.com
--------------------
suzy
giraffe
78910
suzy@giraffe.com
--------------------
我需要将该文件创建一个如下所示的二维字典:
dict = {
'donald': {'fname': donald, 'lname': duck, 'phone': 123456, 'email': donald@duck.com}
'suzy': {'fname': suzy, 'lname': giraffe, 'phone': 78910, 'email': suzy@giraffe.com}
}
程序应该使用第一个名称并使用它创建一个键,然后再取出其他所有内容,包括第一个名称,并创建第二个字典,其他键作为键的元素。当它到达“--------------------”时,它应该重新开始这个过程。目标是能够使用字典:
dict['donald']['phone'] = 123456
dict['suzy']['email'] = suzy@giraffe.com
我到目前为止,我从文件中取出所有内容,并在从字符串中删除换行符后将其放入列表中。
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)
任何想法??
答案 0 :(得分:1)
作为一种快速解决方案,我会做类似的事情:
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"
输出:
{'donald': {'lname': 'duck', 'phone': '123456', 'email': 'donald@duck.com'}, 'suzy': {'lname': 'giraffe', 'phone': '78910', 'email': 'suzy@giraffe.com'}}
{'lname': 'duck', 'phone': '123456', 'email': 'donald@duck.com'}
donald@duck.com
答案 1 :(得分:1)
您可以使用常见的字符串操作( split()
, strip()
等)来执行此操作:
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
使用 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
两种情况的输出相同:
{
'donald': {
'phone': '123456',
'first_name': 'donald',
'last_name': 'duck',
'email': 'donald@duck.com'
},
'suzy': {
'phone': '78910',
'first_name': 'suzy',
'last_name': 'giraffe',
'email': 'suzy@giraffe.com'
}
}
答案 2 :(得分:1)
用词汇理解:
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})
输出:
{
"suzy": {
"email": "suzy@giraffe.com",
"fname": "suzy",
"lname": "giraffe",
"phone": "78910"
},
"donald": {
"email": "donald@duck.com",
"fname": "donald",
"lname": "duck",
"phone": "123456"
}
}