嵌套字典的字符串格式 [英] String formatting with nested dictionary

查看:67
本文介绍了嵌套字典的字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过字符串格式从嵌套字典中写入多个键和相关值。我尝试了各种方法,但由于嵌套,我似乎运气不高。

I'm trying to write multiple keys and associated values from a nested dictionary via string formatting. I have tried various approaches but as it is nested I don't seem to be having much luck. Is this possible?

嵌套词典

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'].


推荐答案

遍历字典以访问其内容。您可以使用 items()词典方法一起遍历其键和值:

Loop through the dictionary to access its contents. You can use the items() dictionary method to loop through its keys and values together:

>>> a = collections.defaultdict(None, {'Devicename1': {'OS': 'version', 'Name': 'name'}, 'Devicename2': {'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>
... '''
>>> for key,d in a.items():
...     print(HEADER.format(key, d['Name'], d['OS']))
...

<html>
    <head>
        <h2>Summary</h2>
        <tr>
        <td><b>Device:</b> Devicename2</td>
        </tr>
        <table style="width:80%">
        <tr>
         <td><b>Name:</b> name</td>
         <td><b>OS:</b> version</td>
        </tr>
        </table>
    </head>
    <body>


<html>
    <head>
        <h2>Summary</h2>
        <tr>
        <td><b>Device:</b> Devicename1</td>
        </tr>
        <table style="width:80%">
        <tr>
         <td><b>Name:</b> name</td>
         <td><b>OS:</b> version</td>
        </tr>
        </table>
    </head>
    <body>

这篇关于嵌套字典的字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆