You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible Playbook中保留字典列表的重复字典

在Ansible Playbook中提取字典列表的重复项

我有一个包含字典的列表,希望只保留其中重复出现的字典。示例数据如下:

{   
   "l": [
        {
            "a": "d",
            "b": "e",
            "c": "f"
        },
        {
            "a": "ggg",
            "b": "hhh",
            "c": "iii"
        },
        {
            "a": "jjj",
            "b": "kkk",
            "c": "lll"
        },
        {
            "a": "d",
            "b": "e",            
            "c": "f"
        }
        ]
}

我试过多种方法,但感觉都是在重复造轮子,也没找到合适的模块。

补充说明
我用jq实现了一个方案,但不够优雅——因为要为每个元素重新遍历处理列表,还得先生成null再过滤。列表被放在data对象里,因为过滤器需要显式引用这个列表。实现代码如下:

---
- name: Filter duplicates from a list of dictionaries
  hosts: localhost
  gather_facts: no
  vars:
    jq_filter: '[ .l[] as $item | if ((.l | map(select(. == $item)) | length) > 1) then $item else null end | select (. != null) ] | unique'
    data:
      l:
        - { a: "ddd", b: "eee", c: "fff" }
        - { a: "ggg", b: "hhh", c: "iii" }
        - { a: "jjj", b: "kkk", c: "lll" }
        - { a: "ddd", b: "eee", c: "fff" }
        - { a: "jjj", b: "kkk", c: "lll" }
  tasks:
    - name: debug list
      debug:
        var: data
    - name: Process list
      shell: echo '{{ data | to_json }}' | jq '{{ jq_filter }}'
      register: shell_output
    - name: get duplicates
      set_fact:
        duplicates: "{{ shell_output.stdout_lines | join | from_json }}"
    - name: debug duplicates
      debug:
        var: duplicates 

我最终采纳了使用自定义过滤器的解决方案

内容的提问来源于stack exchange,提问作者Emmanuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 06:36:14