YAML key consisting of a list of elements

后端 未结 2 778
误落风尘
误落风尘 2021-01-16 22:10

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):

2条回答
  •  星月不相逢
    2021-01-16 22:33

    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.

提交回复
热议问题