Search code examples
pythonlistdictionaryimaplib

Create dictionary key/value pairs from a list based on a condition


Forgive me if this is a mess, but i'm still kind of new. I need to create new variables from data in an email. I am using imaplib to read emails of work tickets on our server. I have been able to pull the data that I need from the emails, but now I have to organize it into something usable. This is the code that I used to get the data;

dataList = []

def parser(data):
    # this will parse the data from ticket and create a list.
    html = data
    parsed = bs(html, "lxml")
    data = [line.strip() for line in parsed.stripped_strings]
    dataList.append(data)


imapUser = "domain\\ticketemailaccount"
imapPassw = "passwordthatisused"
conn = imaplib.IMAP4_SSL('mail.company.com', 993)
try:
    conn.login(imapUser, imapPassw)
except:
    print "##########  SERVER LOGIN ERROR  ##########"
    print sys.exc_info()[1]
    sys.exit(1)

conn.select(readonly=1)
result, data = conn.search(None, '(UNSEEN)')
conn.select("inbox")
ids = data[0].split() #each email has a sequential ID.

for d in ids:
    result, data = conn.fetch(d, "(UID BODY.PEEK[TEXT])")
    raw_email = data[0][1]
    msg = email.message_from_string(raw_email)
    tic = str(msg)
    parser(tic)

for i in dataList:
    ticketNum = i[1] #this is a unique ID for each ticket
    print ticketNum
    print i

The output of this looks like this;

181693185
[u'From nobody Mon Jun 18 10:07:54 2018', u'121314151', u'WORK TICKET REQUEST', u'TICKET NUMBER:', u'181694524', u'OLD TICKET NUM:', u'Message Type:', u'Normal', u'For Code:', u'TRUCK1', u'Hours Notice:', u'72', u'Seq Num:', u'10', u'Prepared By:', u'Bob.1234', u'Call Back:', u'Work Information', u'State:', u'ZA', u'Work To Begin:', u'06/21/18 AT 10:00', u'County:', u'SOMECOUNTY', u'Update Date:', u'07/02/18 AT 00:00', u'Place:', u'GOTHAM CITY', u'Extent:', u"Add'l Addr In Remarks:", u'No'] 

The question I have is, how do I look over the list and create key/value pairs of two items only if the first item encountered ends with a ":", making the following item in the list the value only if it doesn't end with a ":"?


Solution

  • Here's one way using a for loop with zip:

    L = [u'From nobody Mon Jun 18 10:07:54 2018', u'121314151', u'WORK TICKET REQUEST', u'TICKET NUMBER:', u'181694524', u'OLD TICKET NUM:', u'Message Type:', u'Normal', u'For Code:', u'TRUCK1', u'Hours Notice:', u'72', u'Seq Num:', u'10', u'Prepared By:', u'Bob.1234', u'Call Back:', u'Work Information', u'State:', u'ZA', u'Work To Begin:', u'06/21/18 AT 10:00', u'County:', u'SOMECOUNTY', u'Update Date:', u'07/02/18 AT 00:00', u'Place:', u'GOTHAM CITY', u'Extent:', u"Add'l Addr In Remarks:", u'No']
    
    d = {}
    
    for i, j in zip(L, L[1:]):
        if i.endswith(':') and not j.endswith(':'):
            d[i] = j
    

    You can also write this as a dictionary comprehension:

    d = {i: j for i, j in zip(L, L[1:]) if i.endswith(':') and not j.endswith(':')}
    

    Result:

    print(d)
    
    {"Add'l Addr In Remarks:": 'No',
     'Call Back:': 'Work Information',
     'County:': 'SOMECOUNTY',
     'For Code:': 'TRUCK1',
     'Hours Notice:': '72',
     'Message Type:': 'Normal',
     'Place:': 'GOTHAM CITY',
     'Prepared By:': 'Bob.1234',
     'Seq Num:': '10',
     'State:': 'ZA',
     'TICKET NUMBER:': '181694524',
     'Update Date:': '07/02/18 AT 00:00',
     'Work To Begin:': '06/21/18 AT 10:00'}