如何创建包含文本文件中的键值对的字典 [英] How to create a dictionary that contains key‐value pairs from a text file

查看:142
本文介绍了如何创建包含文本文件中的键值对的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件(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):

  1. mattis:turpis
  2. Aliquam:配水
  3. nonummy:ligula
  4. Duis:ultricies
  5. nonummy:pretium
  6. urna:dolor
  7. odio:mauris
  8. lectus:per
  9. quam:ridiculus
  10. tellus:nonummy
  11. consequat:metus
  1. mattis:turpis
  2. Aliquam:adipiscing
  3. nonummy:ligula
  4. Duis:ultricies
  5. nonummy:pretium
  6. urna:dolor
  7. odio:mauris
  8. lectus:per
  9. quam:ridiculus
  10. tellus:nonummy
  11. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆