Python Forum
Need help for extractring keys from dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Need help for extractring keys from dictionary (/thread-15588.html)



Need help for extractring keys from dictionary - dragan979 - Jan-23-2019

Have this code:

if mail["Subject"].find("Alert for  Ta*** prod errors") > 0 :
          body = get_autosys_body(mail)
          info = {}
          segments = body.split(' ')
          for line in body.splitlines():
            if 'Application name' and 'null' in line:
                 info['test'] = segments[0] + ' ' + segments[1] + ' ' + segments[2]  + ' ' + segments[3] + ' ' + segments[4]
            elif 'Application name' in line:
                 info['test'] = segments[0] + ' ' + segments[1] + ' ' + segments[2]  + ' ' + segments[3] + ' ' + segments[4] + ' ' + segments[5] + segments[6] + ' ' + segments[7] +  ' ' + segments[8] + ' ' + segments[9]
          print (info)
which created info dictionary:

{'test': '\r\nApplication name: Ta***\r\nSource: eggs***\r\nTimestamp: 2019-***\r\nMessage:'}
{'test': '\r\nApplication name: Ta***\r\nSource: ***\r\nTimestamp: 2019-***\r\nMessage: HTTP"GET" "/api/fx/pr***/groups" responded 500'}
How to get Values after Application name, source and message (for second line example)

Ta***
HTTP"GET" "/api/fx/pr***/groups" responded 500'


RE: Need help for extractring keys from dictionary - Larz60+ - Jan-23-2019

print(info.keys())
code in loop overwrites key 'test' on each iteration


RE: Need help for extractring keys from dictionary - hbknjr - Jan-23-2019

To get those values you can try:

# For second example where
# info={'test': '\r\nApplication name: Cl***\r\nSource: adc***\r\nTimestamp: 2019-***\r\nMessage: HTTP"GET" "/api/fx/pr***/groups" responded 500'}
data = dict(i.split(':',maxsplit=1) for i in info['test'].strip().split("\r\n"))
print(data['Application name'])
print(data['Source'])
print(data['Message'])



RE: Need help for extractring keys from dictionary - buran - Jan-23-2019

Note that
if 'Application name' and 'null' in line:
may note behave as you expect
'Application name' is non-empty string so it is always considered True. That's why your condition is effectivery just
if 'null' in line:
If you want both 'Application name' and 'null' to be present in the line, then use
if 'Application name' in line and 'null' in line: