[英]How to print every key and value from a dictionary when the value is a list?
[英]How to loop through a list of dictionary, and print out every key and value pair in Ansible
我在 Ansible 配置中有一个字典列表
myList
- name: Bob
age: 25
- name: Alice
age: 18
address: USA
我把代码写成
- name: loop through
debug: msg ="{{item.key}}:{{item.value}}"
with_items: "{{ myList }}"
我想打印出来
msg: "name:Bob age:25 name:Alice age:18 address:USA"
如何遍历此字典并获取键值对? 因为它不知道什么是关键。 如果我更改为 {{ item.name }},ansible 将起作用,但我也想知道 key
如果要遍历列表并分别解析每个项目:
- debug: msg="{{ item | dictsort | map('join',':') | join(' ') }}"
with_items: "{{ myList }}"
将打印:
"msg": "age:25 name:Bob"
"msg": "address:USA age:18 name:Alice"
如果要将所有内容合并为一行,请使用:
- debug: msg="{{ myList | map('dictsort') | sum(start=[]) | map('join',':') | join(' ') }}"
这将给出:
"msg": "age:25 name:Bob address:USA age:18 name:Alice"
请记住,dicts 不在 Python 中排序,因此您通常不能期望您的项目与 yaml 文件中的顺序相同。 在我的示例中,它们在 dictsort 过滤器之后按键名排序。
这是您的文本:myList - 姓名:鲍勃年龄:25 - 姓名:爱丽丝年龄:18 地址:美国
这是答案:
text='''myList - 姓名:鲍勃年龄:25 - 姓名:爱丽丝年龄:18 地址:美国'''
>>> final_text=''
对于 text.split('\\n') 中的行: line1=line.replace(' ','').replace('-','') 如果 'myList' 不在 line1 中: final_text+=line1+' '
final_text '姓名:鲍勃年龄:25 姓名:爱丽丝年龄:18 地址:美国'
class Person(object):
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
def __str__(self):
# String Representation of your Data.
return "name:%s age:%d address:%s" % (self.name, self.age, self.address)
然后你可以有一个你创建的对象列表。 我在这里使用一些示例数据来创建一个字典列表。
dict={"name":"Hello World", "age":23, "address":"Test address"}
myList = [dict,dict,dict]
objList = []
for row in myList:
objList.append(str(Person(**row)))
result = ' '.join(objList)
print(result)
最终打印:姓名:Hello World 年龄:23 地址:测试地址名称:Hello World 年龄:23 地址:测试地址名称:Hello World 年龄:23 地址:测试地址
我打算做 REPR,但它的使用方式有点不同,我认为这可能更适合您的需求。
如果你想保持它非常简单,你可以这样做:
dict={"name":"Hello World", "age":23, "address":"Test address"}
myList = [dict,dict,dict]
objList = []
for row in myList;
tmp = []
for k in row:
tmp.append("%s:%s" % (k, row[k]))
objList.append(" ".join(tmp))
print(" ".join(objList))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.