gpt4 book ai didi

dictionary - Ansible - 如何比较两个具有相同键的字典

转载 作者:行者123 更新时间:2023-12-05 02:10:40 27 4
gpt4 key购买 nike

我有两个字典:

source_list:
myFlag1: true
MyFlag2: false

第二个字典:

target_list:
MyFlag1: false
MyFlag2: false

key 总是相同的,但顺序并不严格。我怎样才能突出它们之间的区别?我可以使用 dict2items 将列表转换为

source_list:
- key: MyFlag1
value: true
- key: MyFlag2
value: false

但是我又很困惑,我怎么比较它们……当然,我可以循环遍历两个字典并一个一个地比较它,但它看起来并不是很有效。任何帮助将不胜感激!

最佳答案

问题:“如何比较具有相同键值的两个字典?”

A:给定简化数据进行测试

    s:
flag1: true
Flag3: true
flag2: false
t:
flag3: true
flag1: false
flag2: false
  • 比较变量以简要找出是否存在任何差异,例如
    - debug:
msg: The dictionaries are identical
when: s == t
- debug:
msg: The dictionaries are different
when: s != t

给予

  msg: The dictionaries are different
  • 接下来,比较键,例如声明变量
    s_keys: "{{ s.keys()|list }}"
t_keys: "{{ t.keys()|list }}"
diff_keys: "{{ s_keys|symmetric_difference(t_keys) }}"

并测试symmetric_difference

的长度
    - debug:
msg: "The difference in the keys: {{ diff_keys }}"
when: diff_keys|length != 0

给予

  msg: 'The difference in the keys: [''Flag3'', ''flag3'']'
  • 让我们假设字典具有相同的键来查找不同的值,例如
    s:
flag1: true
flag3: true
flag2: false
t:
flag3: true
flag1: false
flag2: false
  • 迭代键列表并逐项比较字典,例如
    - debug:
msg: "{{ item }} is {{ (s[item] == t[item])|ternary('OK', 'KO') }}"
loop: "{{ s.keys()|sort }}"
when: diff_keys|length == 0

给予

  msg: flag1 is KO
msg: flag2 is OK
msg: flag3 is OK

问题:“我怎样才能突出它们之间的区别?”

A:创建一个只包含不同值的字典,例如

    - set_fact:
diff_vals: "{{ diff_vals|d({})|combine({item: s[item]}) }}"
loop: "{{ s.keys()|sort }}"
when:
- diff_keys|length == 0
- s[item] != t[item]
- debug:
var: diff_vals

给予

  diff_vals:
flag1: true

<支持>

完整剧本的示例

- hosts: localhost
gather_facts: false

vars:
s:
flag1: true
flag3: true
flag2: false
t:
flag3: true
flag1: false
flag2: false

s_keys: "{{ s.keys()|list }}"
t_keys: "{{ t.keys()|list }}"
diff_keys: "{{ s_keys|symmetric_difference(t_keys) }}"

tasks:

- debug:
msg: The dictionaries are identical
when: s == t
- debug:
msg: The dictionaries are different
when: s != t

- debug:
msg: "The difference in the keys: {{ diff_keys }}"
when: diff_keys|length != 0

- debug:
msg: "{{ item }} is {{ (s[item] == t[item])|ternary('OK', 'KO') }}"
loop: "{{ s.keys()|sort }}"
when: diff_keys|length == 0

- set_fact:
diff_vals: "{{ diff_vals|d({})|combine({item: s[item]}) }}"
loop: "{{ s.keys()|sort }}"
when:
- diff_keys|length == 0
- s[item] != t[item]
- debug:
var: diff_vals

关于dictionary - Ansible - 如何比较两个具有相同键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58486761/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com