zeepi zeepi - 3 months ago 8
Python Question

python nested list comprehension and text formating

I am having some difficulty trying to format data extracted from a dictionary, which will be used to compose an email.
I am trying to use list comprehension to a) minimize the amount of code sent to the email function and b) to remove the outer brackets on my dictionary values and insert a newline;

Code:

test_dict = {'A': [['ap11', 'ct1', 'status a'],
['ap2', 'ct2', 'status b'],
['ap11', 'ct1', 'status a']],
'B': [['ap33', 'ct3', 'status b']]}

for k, v in test_dict.iteritems():
site_id = k
alert_header = str(['aname', 'cname', 'status'])
ap_list = [i for i in v]
# SendMail(site_id, alert_header, ap_list)
print(site_id)
print(alert_header)
print(ap_list)


Output:

A
['aname', 'cname', 'status']
[['ap11', 'ct1', 'status a'], ['ap2', 'ct2', 'status b'], ['ap11', 'ct1', 'status a']]
B
['aname', 'cname', 'status']
[['ap33', 'ct3', 'status b']]


Desired Output is a single string comprising of the key, the alert_header and the str representation of each sublist, one per line:

A
['name', 'cname', 'status']
['ap11', 'ct1', 'status a']
['ap2', 'ct2', 'status b']
['ap11', 'ct1', 'status a']
B
['name', 'cname', 'status']
['ap33', 'ct3', 'status b']


TIA

Answer

To get a single string to send:

test_dict = {'A': [['ap11', 'ct1', 'status a'],
                   ['ap2', 'ct2', 'status b'],
                   ['ap11', 'ct1', 'status a']],
             'B': [['ap33', 'ct3', 'status b']]}

alert_header = str(['aname', 'cname', 'status'])

for site_id, v in test_dict.iteritems():
    # call str on each sublist and separate by newlines.
    data = "\n".join(map(str, v)) 
    # concatenate all three stings into one.
    to_send = site_id + "\n" + alert_header + "\n" + data
    print(to_send)

Output:

A
['aname', 'cname', 'status']
['ap11', 'ct1', 'status a']
['ap2', 'ct2', 'status b']
['ap11', 'ct1', 'status a']
B
['aname', 'cname', 'status']
[['ap33', 'ct3', 'status b']]
Comments