多列文本文件到字典

Text File to Dictionary with multiple columns

我有一个包含以下内容的文本文件

姓氏、名字、电子邮件、一些任意 ID 号和一个 phone 号码。

希尔、乔纳、乔纳希尔@outlook.com、015666、123-456-7890

雷诺兹,瑞安,rrdp@yahoo.com,1081254,789-456-1230

Baccarin,Morena, bmdp@yahoo.com, 1011340, 159-753-4561

...

我想为每一行制作一个字典,但是有键来命名,例如姓氏、名字等

这是我正在尝试的代码

d = {}

with open("oldFile.txt") as f:

d = dict(x.rstrip().split(None, 1) for x in f)

print d 

我得到这样的结果,文件中的所有内容都在一个完整的字典中

{'"hil"': '"jonah" "jonahhill@outlook" "015666" "123-456-7890"'...}

我要找的结果是

第一人称:

{姓氏:"hill",名字:"Jonah",电子邮件:“jonahhill@outlook.com...}

第二人称:

{雷诺兹、瑞安、rrdp@yahoo.com、1081254、789-456-1230}

第三人称: ...

我想要按键将它们单独打印出来,例如

在 file1 中打印出第一人称,我得到

第一人称:

{姓氏:"hill",名字:"Jonah",电子邮件:“jonahhill@outlook.com...}

你需要zip.

keys = ['lastname', 'firstname', 'email', 'id', 'phone']
dicts = []
with open("oldFile.txt") as f:
    for line in f:
        # Split each line.
        line = line.strip().split()
        # Create dict for each row.
        d = dict(zip(keys, line))
        # Print the row dict
        print d
        # Store for future use
        dicts.append(d)

每行的词典在列表 dicts 中可用。

像这样应该可以完成工作:

keys = ['lastname', 'firstname', 'email', 'id', 'phone']
file = open('oldFile.txt', 'r')
results = []
while True:
    line = file.readline()
    if not line:
        break
    else:
        content = line.split(', ')
        dict = {}
        index = 0
        for value in content:
            if value != '\n':
                pair = {keys[index]: value}
                dict.update(pair)
                index += 1
        if dict != {}:                          # Prevent empty lines from appending to results
            results.append(dict)

for dict in results:
    print dict