如何从文本文件创建字典并在python中添加值?

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

我有一个文本文件,其中包含以下内容

a
b
c
d

如何创建字典并添加值,使其如下所示:

a is 1,
b is 2,
c is 3,
d is 4

我是初学者,所以我试图按照这里的指南,但所有文本文件包含像a 1 b 2 c 3但我的是a b c d

python file dictionary
1个回答
0
投票

使用理解:

with open(your_file_name, "r") as f:
     data = {k: l for l, k in enumerate(f, 1)}
© www.soinside.com 2019 - 2024. All rights reserved.