【问题标题】:Is it possible to use a tuple as a dictionary key in Python YAML?是否可以在 Python YAML 中使用元组作为字典键?
【发布时间】:2015-01-22 08:21:49
【问题描述】:
dictionary = {('x1','y1'): [1,2], ('x2','y2'): [4,5], ('x3','y3'): [6,7]}

如何在 Python YAML 中配置这种字典?

【问题讨论】:

  • 也许,如果元组中只有字符串,您可以将它们加入 "_".join(a_tuple) 并使用结果字符串作为键。

标签: python dictionary yaml


【解决方案1】:

一种选择是创建您的 YAML 文件,例如:

!!python/tuple ['x1','y1']: [1,2]
!!python/tuple ['x2','y2']: [4,5]
!!python/tuple ['x3','y3']: [6,7]

然后加载它:

import yaml

print yaml.load(stream=open("your_file_path", 'r'))

输出:

{('x1', 'y1'): [1, 2], ('x3', 'y3'): [6, 7], ('x2', 'y2'): [4, 5]}

要获得一些价值,您可以使用:

yaml_load[('x1', 'y1')]

如果你想测试它是一个元组,只需使用:

type(yaml_load.keys()[0])

【讨论】:

  • 是否可以用这种格式转储它 "!!python/tuple ['x1','y1']: [1,2]" 显然:{(1,2): [ 1,2,3]} == yaml.load(yamp.dump({(1,2): [1,2,3]}))
猜你喜欢
  • 1970-01-01
  • 2013-10-14
  • 2014-04-14
  • 2018-03-30
  • 1970-01-01
  • 2012-03-18
  • 2014-07-30
  • 1970-01-01
  • 2011-10-25
相关资源
最近更新 更多