简体   繁体   中英

Finding a dictionary value in a list and appending the matching key with list comprehension

I am new to Python and wondering how to solve this...

I have a dictionary called tagsDic that has a cancellation reason as a key and a tag id as a value.

I am querying contacts from my CRM and storing them in a list (allcancelledmembers). If a value from tagsDic is in the record, I want to add the matching key to each record in the list.

The value would be in the Contact.Groups field and the query returns a string of every tag id the contact has like '123,233,455,1123,5569,10123'.

So if ',10738' is in the Contact.Groups, I would want to add 'Unknown' to that record.

Is there a way to do this using list comprehension in the last row of my code?

This is an example of a record in allcancelledmembers:

{'Contact.OwnerID': 28950, 'Contact.Groups': '128,138,206,208,312,420,493,790,952,1528,1554,3286,3302,3634,4090,6566,6570,6572,6576,6578,6582,6584,6588,6596,6600,6604,6606,6608,6610,6614,6766,6782,6784,6934,6966,6970,6972,6992,7054,7060,7062,7226,7366,7688,7692,7906,8006,8010,8122,8130,8254,8274,8282,8290,8418,8644,8672,8734,8873,9041,9043,9171,9175,9540,9622,9752,10738', 'DateCreated': <DateTime '20190513T17:28:05' at 0x10dbec5c0>, 'Contact.Id': 621894}

And this is what I would like to have returned with the last line with lc_allcancelmembers:

[18526, datetime.datetime(2019, 4, 16, 10, 49, 22), 327378, '130,132,134,136,138,140,154,206,208,290,312,493,762,788,882,952,968,1002,1088,1226,1234,2610,2972,2974,3102,6034,6950,8222,8282,8292,8412,8418,8610,8672,8931,9121,9542,9734,9740,9754,10738', 'Unknown']

'Unknown' is added to the end of the record in lc_allcancelmembers because ',10738' was in the Contact.Groups field in allcancelledmembers.

Thanks!

Here is the code I'm working with: '''

limit = 1000
searchPage = 0
tagId = 493
table = 'ContactGroupAssign'
selectedFields = ['Contact.Id', 'DateCreated', 'Contact.OwnerID', 'Contact.Groups']
queryDataUnknown = {'GroupId': tagId, 'DateCreated': "~>=~" + str(twoyearsago)}

tagsDic = {'Unknown': ',10738', 
'Cant Afford': ',10712', 
'Doesnt Want To Pay': ',10714', 
'No 3rd Party': ',10716', 
'No Longer Qualifies': ',10718', 
'Scam': ',10720', 
'No Contact': ',10734', 
'Collections - Non Payment': ',7878', 
'Billing Cancellation': ',10748', 
'NBDK': ',8744', 
'Within 5 Days: Cant Afford CTF': ',10744', 
'Within 5 Days: Changed Mind/Persuaded': ',10746'}

allcancelledmembers = []
while True:
        queryResults = infusionsoft.DataService('query', table, limit, searchPage, queryDataUnknown, selectedFields)
        allcancelledmembers += queryResults
        searchPage += 1
        if len(queryResults) < 1000:
            break
lc_allcancelmembers =[[record.get("Contact.Id"),convert_is_datetime(str(record.get("DateCreated")))record.get("Contact.OwnerID"),record.get("Contact.Groups")] for record in allcancelledmembers]

'''

Assuming your code is correct, this is how to implement it in a list comprehension:

From:

allcancelledmembers = []
while True:
        queryResults = infusionsoft.DataService('query', table, limit, searchPage, queryDataUnknown, selectedFields)
        allcancelledmembers += queryResults
        searchPage += 1
        if len(queryResults) < 1000:
            break

To:

allcancelledmembers = [p for s in [infusionsoft.DataService('query', table, limit, searchPage, queryDataUnknown, selectedFields) if len(infusionsoft.DataService('query', table, limit, searchPage, queryDataUnknown, selectedFields))<1000 else None for searchPage in range(1000)] for p in s][:allcancelledmembers.index(None)]

You could swap key:value pairs of your tagsDic aswell:

tagsDic2 = {value:key for key,value in tagsDic.items()}

Alternatively you could do something like this in your list comprehension:

d = {'1':'a', '2':'b'}
print([a[0] for a in d.items() if a[1]=='b' ][0])

print([a[0] for a in d.items() for x in ['a', 'c', 'd', 'b'] if x==a[1] ])

which returns the key of the (key, value) pairs, however i would strongly advise against it. Its highly inefficient for large dictionaries or a lot of queries.

[a[0] for a in tagsDic.items() for x in record.get("Contact.Groups").split(',') if x==a[1] ]

Add this in 'Unknown' if '10738' in record.get('Contact.Groups') else '' your list comprehension code.

It will add 'Unknown' to the list if '10738' in 'Contact.Groups' else it will add an empty string.

lc_allcancelmembers = [[record.get("Contact.Id"), convert_is_datetime(str(record.get("DateCreated"))), record.get("Contact.OwnerID"), record.get("Contact.Groups"), [k for k, v in tagsDic.items() if v in record.get("Contact.Groups")][0]] for record in allcancelledmembers]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM