Grygger
Grygger

Reputation: 93

Split a dictionary to explictly call out 'Key' : dict.keys() and "Value' : dict.values() for JSON data going into an API

I'm currently working with the CampaignMonitor API to support with email subscription management and email marketing. I need to send JSON data through the API to make any changes to the subscription list. My current code looks like the following,

df = test_json.groupby(['EmailAddress', 'Name']).apply(lambda x : x[['Location', 'location_id', 'customer_id', 'status','last_visit'].astype(str).to_dict(orient = 'records'))
df = df.reset_index().rename(columns = {0 : 'CustomFields'})
#df['CustomFields'].apply(lambda x : print(x[0].items()))

Which returns the following

{‘EmailAddress’ : ‘[email protected]’, ‘Name’ : ‘John Smith’, ‘CustomFields’ : [{'Location': 'H6GO', location_id': 'D8047', 'customer_id': '2963', 'status': 'Active', 'last_visit': '2020-06-23'}]}

However, the Campaign Monitor API specifically wants for the CustomFields to contain an explicit call out for the key and value of each dictionary pairing. Is there a simple way to expand an existing dictionary and create a sub dictionary within a dictionary calling out the the key and value? Right now, I'm thinking of using apply to do it row by row but am struggling for how to break these down so the key and value callouts remain in one dictionary,

{‘EmailAddress’ : ‘[email protected]’, ‘Name’ : ‘John Smith’, ‘CustomFields’ : [{‘Key’ : 'Location', ‘Value’ : 'H6GO'},
{‘Key’ : ‘location_id' , ‘Value’ : 'D8047'}, 
{‘Key’ : 'customer_id', ‘Value’ : '2963'}, 
{‘Key’ : 'status', ‘Value’ : 'Active'}, 
{‘Key’ : 'last_visit', ‘Value’ : '2020-06-23'}
]}

Upvotes: 0

Views: 31

Answers (2)

Paul Bombarde
Paul Bombarde

Reputation: 311

You need to transform your list with one dict into a list containing N 'key,value' dicts. You may use a generator like this

reformated = [{"Key":k, "Value":v} for k, v in original_dict.items()]

for example :

>>> od = {'Location': 'H6GO', 'location_id': 'D8047', 'customer_id': '2963', 'status': 'Active', 'last_visit': '2020-06-23'}
>>> reformated = [{"Key":k, "Value":v} for k, v in od.items()]
>>> reformated
[{'Key': 'Location', 'Value': 'H6GO'}, {'Key': 'location_id', 'Value': 'D8047'}, {'Key': 'customer_id', 'Value': '2963'}, {'Key': 'status', 'Value': 'Active'}, {'Key': 'last_visit', 'Value': '2020-06-23'}]

Upvotes: 1

Roy2012
Roy2012

Reputation: 12523

Try this:

d["CustomFields"] = [{"key": k, "value": v} for k,v in d["CustomFields"][0].items()]

output:

{'EmailAddress': '[email protected]',
 'Name': 'John Smith',
 'CustomFields': [{'key': 'Location', 'value': 'H6GO'},
  {'key': 'location_id', 'value': 'D8047'},
  {'key': 'customer_id', 'value': '2963'},
  {'key': 'status', 'value': 'Active'},
  {'key': 'last_visit', 'value': '2020-06-23'}]}

Upvotes: 2

Related Questions