将包含字符串的文本文件转换为字典

时间:2018-03-05 22:47:43

标签: python python-2.7 dictionary

我想知道如何将包含字符串的文本文件转换为字典。我的文本文件如下所示:

Donald Trump, 45th US President, 71 years old Barack Obama, 44th US President, 56 years old George W. Bush, 43rd US President, 71 years old

我希望能够将该文本文件转换为字典:

{Donald Trump: 45th US President, 71 years old, Barack Obama: 44th US President, 56 years old, George W. Bush: 43rd US President, 71 years old}

我该怎么做呢?谢谢!

我尝试这样做:

d = {} with open('presidents.txt', 'r') as f: for line in f: key = line[0] value = line[1:] d[key] = value

2 个答案:

答案 0 :(得分:0)

这是你要找的吗?

d = {}

with open("presidents.txt", "r") as f:
    for line in f:
        k, v, z = line.strip().split(",")
        d[k.strip()] = v.strip(), z.strip()
f.close()
print(d)

最终输出如下:

{'Donald Trump': ('45th US President', '71 years old'), 'Barack Obama': ('44th US President', '56 years old'), 'George W. Bush': ('43rd US President', '71 years old')}

答案 1 :(得分:0)

您可以使用pandas

import pandas as pd

df = pd.read_csv('file.csv', delimiter=', ', header=None, names=['Name', 'President', 'Age'])

d = df.set_index(['Name'])[['President', 'Age']].T.to_dict(orient='list')

# {'Barack Obama': ['44th US President', '56 years old'],
#  'Donald Trump': ['45th US President', '71 years old'],
#  'George W. Bush': ['43rd US President', '71 years old']}