gpt4 book ai didi

csv - 如何将键值对添加到列表中的每个字典

转载 作者:行者123 更新时间:2023-12-04 07:41:28 25 4
gpt4 key购买 nike

我必须向从 csv 文件读取到变量的列表中添加一个键和一个值。

为了更好地解释它。首先,我从一个 csv 文件加载一个列表:

- name: Load user list from csv
community.general.read_csv:
path: ../files/example-prod.csv
delimiter: ','
register: users
delegate_to: localhost

当我查看“用户”变量时,我得到以下输出:

"list": [
{
"firstName": "Max",
"gid": "2002",
"homedir": "example",
"lastName": "Mustermann",
"uid": "m.example"
},
{
"firstName": "Martin",
"gid": "2002",
"homedir": "staff",
"lastName": "Muster",
"uid": "martin.muster"
}
]

现在我需要为列表中的所有用户生成密码。所以我想遍历项目并为列表中的每个项目添加一个新的键值对。

密码创建循环后我想要的输出是:

"list": [
{
"firstName": "Max",
"gid": "2002",
"homedir": "example",
"lastName": "Mustermann",
"uid": "m.example",
"password": "examplepassword"
},
{
"firstName": "Martin",
"gid": "2002",
"homedir": "staff",
"lastName": "Muster",
"uid": "martin.muster",
"password": "examplepassword"
}
]

...这样我可以稍后读出变量。

如何实现?我读过很多关于如何使用字典执行此操作的内容,但由于我在这里使用的是列表,所以我找不到它。

最佳答案

您实际上是从 read_csv 中获取字典列表模块。 "list"的内容是一个列表,但是这个列表中的元素是字典。

你要做的是在每个字典中添加一个键值对。
这是生成随 secret 码的示例。查看password-lookup documentation关于它如何生成密码的详细信息:

- set_fact:
users: |
{{ users.list | map('combine', { "password": "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=8') }}"}) }}

# this resolves the template added above and is required to avoid changing passwords on each resolve of users
- set_fact:
users: "{{ users }}"

- debug:
msg: "{{ users }}"

解释:

  • users.list包含您的用户列表
  • map('combine', <dict>)运行 combine过滤输入列表中的每个字典(在本例中为 users.list)并添加 <dict> 的内容对它
  • { "password": "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=8') }}"}是我们将每个输入字典与
  • 组合的字典
  • "password"是键,值是生成密码的查找

备注:
我使用 yaml 的多行字符串文字来避免引用 hell 。

关于csv - 如何将键值对添加到列表中的每个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67431252/

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