Ansible:使用items2dict将列表转换为字典

cloud_hack

给出以下列表:

fruits:
  - fruit: apple
    color: red
    texture: crunchy
    shape: round
  - fruit: grapefruit
    color: yellow
    taste: sour
  - fruit: pear
    color: yellow

我将如何使用items2dict过滤器更改为词典(如下)?问题是存在多个,并且数量可变。

"{{ fruits | items2dict(key_name='fruit', value_name='??????') }}

所需结果:

fruits:
  - apple:
      color: red
      texture: crunchy
      shape: round
  - grapefruit:
      color: yellow
      taste: sour
  - pear:
      color: yellow

我似乎在这里找不到方法:https//docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#transforming-lists-into-dictionaries

弗拉基米尔·博特卡

以下任务完成了任务

    - set_fact:
        fruits2: "{{ fruits2|default([]) + [{ item['fruit']: value }]}}"
      loop: "{{ fruits }}"
      vars:
        keys: "{{ item.keys()|difference(['fruit']) }}"
        vals: "{{ keys|map('extract', item)|list }}"
        value: "{{ dict(keys|zip(vals)) }}"

  fruits2:
  - apple:
      color: red
      shape: round
      texture: crunchy
  - grapefruit:
      color: yellow
      taste: sour
  - pear:
      color: yellow

可以通过简单地将列表的串联更改为字典的组合来创建字典,而不是列表。

    - set_fact:
        fruits3: "{{ fruits3|default({})|combine({ item['fruit']: value }) }}"
      loop: "{{ fruits }}"
      vars:
        keys: "{{ item.keys()|difference(['fruit']) }}"
        vals: "{{ keys|map('extract', item)|list }}"
        value: "{{ dict(keys|zip(vals)) }}"

  fruits3:
    apple:
      color: red
      shape: round
      texture: crunchy
    grapefruit:
      color: yellow
      taste: sour
    pear:
      color: yellow

items2dict只能用于选择2个属性(key_namevalue_name),例如

    - set_fact:
        fruits4: "{{ fruits|items2dict(key_name='fruit', value_name='color') }}"

  fruits4:
    apple: red
    grapefruit: yellow
    pear: yellow

不能创建列表(所需结果)items2dictitems2dict返回字典。


items2dict 如果属性丢失,将失败,例如

    - set_fact:
        fruits5: "{{ fruits|items2dict(key_name='fruit', value_name='taste') }}"

失败了

The error was: KeyError: 'taste'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章