我想通过字符串格式化从嵌套字典中写入多个键和相关联的值。我尝试了各种方法,但因为它嵌套,我似乎没有多少运气。这可能吗?字符串与嵌套字典格式化
嵌套字典
defaultdict(None, {'Devicename': {'OS': 'version', 'Name': 'name'}, 'Devicename': {'OS': 'version', 'Name': 'name'}})
格式化数据
HEADER = '''
<html>
<head>
<h2>Summary</h2>
<tr>
<td><b>Device:</b> {0}</td>
</tr>
<table style="width:80%">
<tr>
<td><b>Name:</b> {1}</td>
<td><b>OS:</b> {2}</td>
</tr>
</table>
</head>
<body>
'''
写入文件
with open("Summary.html", "w+") as outfile:
outfile.write(HEADER.format(device_dic[0], device_dic['Name'], device_dic['OS']))
#Potentially multiple items of each as shown in test dictionary. The `Devicename` varies so cant be called by string example ['OS'].
如果你不知道你实际需要访问哪些键,什么决定你的'format()'参数? – TigerhawkT3
我需要{0}中的所有键名和{1}中的所有['名称']值以及{2}中的所有['OS']值。 – iNoob
我确实认为我需要在词典中使用iteritems,但是我无法为我的生活制定出如何做到这一点。格式:$ – iNoob