【问题标题】:how do I use 'dict' without list comprehension如何在没有列表理解的情况下使用“dict”
【发布时间】:2018-01-21 05:49:58
【问题描述】:

我是 python 的初学者,如果有人能帮助我理解为什么 dict 与列表理解一起使用而在我的情况下不适用于简单的参数参数,那将是非常有帮助的?两个代码示例都在下面给出,

输入:(我正在从 .txt 文件中读取以下数据并转换为 JSON)

vm4 : Windows10
vm2 : Ubuntu14
vm1 : Ubuntu14
vm3 : MacOSX10.11

工作代码。

file1 = dict(i.split(':') for i in file1.split('\n'))

代码不工作

for i in file1.split('\n'):
    print dict(i.split(':'))

ValueError                                Traceback (most recent call last)
<ipython-input-176-048ba6a1e29b> in <module>()
      1 for i in file1.split('\n'):
----> 2     print dict(i.split(':'))

ValueError: dictionary update sequence element #0 has length 4; 2 is required

【问题讨论】:

  • 如果.txt文件中的数据已经格式化为dict,那么使用eval
  • 如果要读取列表中文件的所有行,也可以使用list(f)f.readlines()
  • 我复制了你 txt 并使用此代码并完美运行:with open("test.txt", "r") as file: file1 = dict(i.split(" : ") for i in file)
  • @GarbageCollector 这非常不安全!不要那样做!
  • 我的代码file1 = dict(i.split(" : ") for i in file) 工作得很好。!但我不明白为什么没有列表理解它就不能工作。!我需要对此进行一些解释..如果有人可以在这里提供帮助。 !我注意到一件事,对于列表理解,我们将整个 for 循环作为 dict 参数传递。对于另一段代码,我们没有这样做..这可能是原因..!

标签: python python-2.7 dictionary


【解决方案1】:

您是否正在尝试将文本文件的内容转换为字典?

如果是这样,这就是你想要的吗:

d = {}
with open("text.txt") as f:  
    for line in f:
        key, value = line.strip().split(' : ')
        d[key] = value
print(d)

输出:

{'vm4': 'Windows10', 'vm2': 'Ubuntu14', 'vm1': 'Ubuntu14', 'vm3': 'MacOSX10.11'}

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2021-10-30
    • 1970-01-01
    相关资源
    最近更新 更多