String formating with nested dictionary

2019-09-10 06:53发布

问题:

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?

Nested Dictionary

defaultdict(None, {'Devicename': {'OS': 'version', 'Name': 'name'}, 'Devicename': {'OS': 'version', 'Name': 'name'}})

Formatting Data

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

Writing To File

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

回答1:

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>


回答2:

The following code uses list iterations [ expr(arg) for arg in list ] to enumerate over the devices, and dictionary unpacking to provide the arguments for format.

from collections import defaultdict

device_dic = defaultdict(None, {'Devicename1': {'OS': 'version1', 'Name': 'name1'}, 'Devicename2': {'OS': 'version2', 'Name': 'name2'}})

HEADER1 = '''
<html>
    <head>
'''

# Split this since we'll have multiple copies
# Note that the {} use named arguments for format here. {OS}, etc.
HEADER2 = '''
        <h2>Summary</h2>
        <tr>
        <td><b>Device:</b> {0}</td>
        </tr>
        <table style="width:80%">
        <tr>
         <td><b>Name:</b> {OS}</td>
         <td><b>OS:</b> {Name}</td>        
        </tr>
        </table>
'''
HEADER3 = '''
    </head>
    <body>
'''

with open("Summary.html", "w+") as outfile:
    outfile.write(HEADER1
                  # We iterate over the items in the dictionary here.
                  # The **value unpacks the nested dictionary. see https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
                  + "".join([HEADER2.format(key, **value) for key, value in device_dic.items()]) \
                  + HEADER3
                  )