如何创建包含文本文件中的键值对的字典 [英] How to create a dictionary that contains key‐value pairs from a text file
问题描述
我有一个文本文件(one.txt),其中包含任意数量的键/值对(键和值之间用冒号分隔,例如x:17).这里是一些(减去数字):
I have a text file (one.txt) that contains an arbitrary number of key‐value pairs (where the key and value are separated by a colon – e.g., x:17). Here are some (minus the numbers):
- mattis:turpis
- Aliquam:配水
- nonummy:ligula
- Duis:ultricies
- nonummy:pretium
- urna:dolor
- odio:mauris
- lectus:per
- quam:ridiculus
- tellus:nonummy
- consequat:metus
- mattis:turpis
- Aliquam:adipiscing
- nonummy:ligula
- Duis:ultricies
- nonummy:pretium
- urna:dolor
- odio:mauris
- lectus:per
- quam:ridiculus
- tellus:nonummy
- consequat:metus
我需要打开文件并创建一个包含所有键值对的字典.
I need to open the file and create a dictionary that contains all of the key‐value pairs.
到目前为止,我已经打开了文件
So far I have opened the file with
file = []
with open('one.txt', 'r') as _:
for line in _:
line = line.strip()
if line:
file.append(line)
我以这种方式打开它,以消除文本文件中的换行符和最后一个黑线.我得到了python中的键/值对的列表.
I opened it this way to get rid of new line characters and the last black line in the text file. I am given a list of the key-value pairs within python.
我不确定如何使用列表键值对创建字典. 我尝试过的一切都给我一个错误.有些人说的是
I am not sure how to create a dictionary with the list key-value pairs. Everything I have tried gives me an error. Some say something along the lines of
ValueError:字典更新序列元素#0的长度为1;需要2个
ValueError: dictionary update sequence element #0 has length 1; 2 is required
推荐答案
使用str.split()
:
with open('one.txt') as f:
d = dict(l.strip().split(':') for l in f)
这篇关于如何创建包含文本文件中的键值对的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!