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

问题描述 投票:1回答:2

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

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

python python-2.7 dictionary
2个回答
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')}


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']}
© www.soinside.com 2019 - 2024. All rights reserved.