【问题标题】:Python Would it be possible to fill a dictionary with multiple keys and values using one string?Python 是否可以使用一个字符串来填充具有多个键和值的字典?
【发布时间】:2014-08-05 23:24:19
【问题描述】:

关键是不要使用 dict.copy(),如果您愿意,可以将其视为挑战。 例如,我有这个字典,我把它转换成一个字符串

Dict = {'Hello':'World', 'Hi':'Again'}
x = str(Dict)

x 是包含字符串的变量。 现在我想将 x 放入字典中,但我必须能够打印单个键('Hello' 和 'Hi')以及值('World' 和 'Again')

Dict2 = {x}
for key, value in Dict2.items() :
    print (key, value)

这不起作用,我知道为什么。 的输出:

for key, value in Dict2.items() :
        print (key, value)

必须与:

for key, value in Dict.items() :
        print (key, value)

【问题讨论】:

  • 我不确定你是否知道,但字典是无序的,所以如果你稍后打印出字典的内容,你不会知道你会得到什么,很可能是Hi again Hello World
  • 只要能独立打印键值就可以了
  • 如果您认为您正在编写的一段代码中需要此功能,那么您需要重新考虑您的问题 - 如上所述,字典是无序的。您可以使用有序字典来执行此操作,并且可能将其子类化以提供解析字符串的函数,并输出为简单的字符串 - 但我不明白您为什么要这样做。
  • 我不是特别需要它,我给自己设定了一个挑战,我被困住了。任何帮助表示赞赏

标签: python string testing dictionary


【解决方案1】:

我认为问题在于Dict2 = {x} 没有做你想做的事。

>>> Dict = {'hello':'world', 'hi':'again'}
>>> x = str(Dict)
>>> x
"{'hi': 'again', 'hello': 'world'}"
>>> Dict2 = {x}
>>> Dict2
set(["{'hi': 'again', 'hello': 'world'}"])

如您所见,它将其转换为集合。
要从字符串创建字典,您可以并且应该使用 ast.literal_eval():

>>> import ast
>>> d = ast.literal_eval("{'hello': 'world', 'hi': 'again'}")
>>> d
{'hi': 'again', 'hello': 'world'}
>>> type(d)
<type 'dict'>

正如安蒂·哈帕拉指出的那样

请注意,ast.literal_eval 仅适用于严格的值子集;此外,str(dict) 根本不保证是无损的,因为它使用__repr__ 作为键和值。

【讨论】:

  • 请注意,ast.literal_eval 仅适用于严格的值子集;此外,str(dict) 根本不保证是无损的,因为它使用__repr__ 作为键和值。
  • @AnttiHaapala 我只是在使用 OP 中的示例,但我还是会添加你的注释,因为它是一个很好的注释
  • 是的,这只是对 OP 的评论
猜你喜欢
  • 2019-06-26
  • 1970-01-01
  • 2017-03-14
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多