YAML key consisting of a list of elements

丶灬走出姿态 提交于 2019-12-30 14:40:49

问题


I need to have a list of elements as a key, so that I can check if several conditions are met. Example (don't know if this is possible and if the syntax is correct):

mapping:
  c_id:
    [pak, gb]: '4711'
    [pak, ch]: '4712'
    [pak]: '4713'
  d_id:
    .
    .
    .

Now I need to know if it is possible to have an approach as in the example.


回答1:


In addition to Anthon's answer, here is how you can do it with PyYaml:

mapping:
  c_id:
    !!python/tuple [pak, gb]: '4711'
    !!python/tuple [pak, ch]: '4712'
    !!python/tuple [pak]: '4713'

The trick is to tell PyYaml that you want to load the keys into a tuple (since a list cannot be used as dict key). There is no way to do this implicitly, but this does not mean that it is not possible.

Explicit keys may be more readable in this case:

mapping:
  c_id:
    ? !!python/tuple [pak, gb]
    : '4711'
    ? !!python/tuple [pak, ch]
    : '4712'
    ? !!python/tuple [pak]
    : '4713'

This example is semantically equivalent to the first one.




回答2:


The syntax for your YAML is correct. The only trick is that because in Python a key has to be immutable you need to specify access to the complex key as a tuple:

import ruamel.yaml

yaml_str = """\
mapping:
  c_id:
    [pak, gb]: '4711'
    [pak, ch]: '4712'
    [pak]: '4713'
"""

data = ruamel.yaml.round_trip_load(yaml_str)
print(data['mapping']['c_id'][('pak', 'gb')])

gives:

4711

Please note that this is not possible with PyYAML, as it doesn't support sequences as keys, you have to use ruamel.yaml (disclaimer: I am the author of that package)



来源:https://stackoverflow.com/questions/39507595/yaml-key-consisting-of-a-list-of-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!