我从 HOSTS 得到以下列表:
"HOSTNAME": [
"H1",
"H2",
"H3"
]
"SW_VERSION": [
"7.2.2",
"5.2.2",
"6.2.2"
]
"OSPF_NEIGHBOR": [
"10.1.1.1",
"10.1.1.2",
"10.1.1.3"
]
我正在将它们转换为 Dict 对象列表,如下所示:(目的是根据我们获得的数据创建报告)
- set_fact:
host_data: "{{ h_data|default([]) + [ { 'HOSTNAME': item.0, 'SW_VERSION': item.1, 'OSPF_NEIGHBOR': item.2} ] }}"
with_together:
- "{{ HOSTNAME }}"
- "{{ SW_VERSION }}"
- "{{ OSPF_NEIGHBOR }}"
我得到如下输出:
"host_data": [
{
"HOSTNAME": "H1",
"OSPF_NEIGHBOR": "10.1.1.1",
"SW_VERSION": "7.2.2"
},
{
"HOSTNAME": "H2",
"OSPF_NEIGHBOR": "10.1.1.2",
"SW_VERSION": "6.2.2"
},
{
"HOSTNAME": "H3",
"OSPF_NEIGHBOR": "10.1.1.3",
"SW_VERSION": "5.2.2"
}
]
我给 HOSTNAME
作为 item.0
,SW_VERSION
作为 item.1
和 OSPF_NEIGHBOR
作为 item.2
,但是 在输出 OSPF_NEIGHBOR
中排在影响表格式/列顺序的字典元素中的第二位。
我们如何确保顺序得到保留?
或者有没有办法根据所需的列顺序重新排列 host_data
列表中的 dict 元素顺序?
最佳答案
我认为这值得回答,因为它不像 @Zeitounator 那样简单最初评论:
Dictionaries don't have order. Said differently you cannot rely on any order the data is spitted out from a dictionary. Use the key name that correspond to the information you need.
实际上,直到 Python 3.6 之前都是如此,其中进行了更改并且:
New
dict
implementationThe dict type now uses a “compact” representation based on a proposal by Raymond Hettinger which was first implemented by PyPy. The memory usage of the new
dict()
is between 20% and 25% smaller compared to Python 3.5.The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).
来源:https://docs.python.org/3/whatsnew/3.6.html#new-dict-implementation
在此基础上,原来在Ansible 2.10版本中加入的一个改动:Add support for OrderedDict已被撤消为 the requirement to have Python 3.8添加了 Ansible。
基于所有这些,我猜你使用的是旧版本的 Ansible(2.10 之前),你的解决方案应该只是升级你的 Ansible 版本,也是因为 the 2.9 branch has been out of support since 31 December 2021 .
关于ansible - 列表的 dict 对象的元素顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72498108/