Python - Extracting information from dictionary in a specific way - python

I am trying to extract certain values from a dictionary and display it a specific way. I'll show you my code example below:
dict = [{'Titel': 'Rush', 'Name': 'Floris', 'Starttime': '20:30', 'Email': 'Floris#email.com', 'Supplier': 'RTL8', 'Surname': 'Cake', 'Code': 'ABC123'},
{'Titel': 'Rush', 'Voornaam': 'Jaron', 'Starttime': '20:30', 'Email': 'JaronPie#email.com', 'Supplier': 'RTL8', 'Surname': 'Pie', 'Code': 'XYZ123'},
{'Titel': 'Underneath', 'Name': 'Klaas', 'Starttime': '04:00', 'Email': 'Klassieboy#gmail.com', 'Supplier': 'RTL8', 'Surname': 'Klassie', 'Code': 'fbhwuq8674'}]
That is my dictionary. What I want as output is:
Titel, Starttime,
Surname, Name, Email
So it would look like this:
Rush, 20:30,
Cake, Floris, Floris#email.com
Pie, Jaron, JaronPie#email.com
Underneath, 04:00,
Klassie, Klaas, Klassieboy#gmail.com

I used VKS's code to build it thanks VKS :P
Using groupy,list comprehension and sting formatting
Code:
from itertools import groupby
k = [{'Titel': 'Rush', 'Name': 'Floris', 'Starttime': '20:30', 'Email': 'Floris#email.com', 'Supplier': 'RTL8', 'Surname': 'Cake', 'Code': 'ABC123'},
{'Titel': 'Rush', 'Voornaam': 'Jaron', 'Starttime': '20:30', 'Email': 'JaronPie#email.com', 'Supplier': 'RTL8', 'Surname': 'Pie', 'Code': 'XYZ123'},
{'Titel': 'Underneath', 'Name': 'Klaas', 'Starttime': '04:00', 'Email': 'Klassieboy#gmail.com', 'Supplier': 'RTL8', 'Surname': 'Klassie', 'Code': 'fbhwuq8674'}]
lst=[(i["Titel"],i["Starttime"],i["Surname"],i.get("Name","None"), i["Email"]) for i in k]
lst.sort(key=lambda x:(x[0],x[1]))
for key,groups in groupby(lst,key=lambda x:(x[0],x[1])):
print "{}\t{}".format(key[0],key[1])
for value in groups:
print "{}\t{}\t{}".format(value[2],value[3],value[4])
print ""
Output:
Rush 20:30
Cake Floris Floris#email.com
Pie None JaronPie#email.com
Underneath 04:00
Klassie Klaas Klassieboy#gmail.com

k = [{'Titel': 'Rush', 'Name': 'Floris', 'Starttime': '20:30', 'Email': 'Floris#email.com', 'Supplier': 'RTL8', 'Surname': 'Cake', 'Code': 'ABC123'},
{'Titel': 'Rush', 'Voornaam': 'Jaron', 'Starttime': '20:30', 'Email': 'JaronPie#email.com', 'Supplier': 'RTL8', 'Surname': 'Pie', 'Code': 'XYZ123'},
{'Titel': 'Underneath', 'Name': 'Klaas', 'Starttime': '04:00', 'Email': 'Klassieboy#gmail.com', 'Supplier': 'RTL8', 'Surname': 'Klassie', 'Code': 'fbhwuq8674'}]
print [(i["Titel"],i["Starttime"],i["Surname"], i["Email"]) for i in k]
You can use this and you will get tuple of all info you want.

def print_my_d(d):
print(d[0]['Titel'], d[0]['Starttime'])
for l in d[:2]:
print(l['Surname'], l['Name'], l['Email'])
print()
print(d[2]['Titel'],d[2]['Starttime'])
print("{}, {}, {}".format(d[2]['Surname'],d[2]['Name'], d[2]['Email']))
print_my_d(d)
Rush 20:30
Cake Floris Floris#email.com
Pie Jaron JaronPie#email.com
Underneath 04:00
Klassie, Klaas, Klassieboy#gmail.com

Related

PayPal webhooks integration with django

I am integrating Paypal in django-rest- framework. The issue is with paypal webhook response. I get a webhook json response when ever I pay some amount on paypal already created a url path in my application for the same.
Sample JSON object response:
{'event_version': '1.0', 'create_time': '2022-12-19T18:57:12.343Z', 'resource_type': 'checkout-order', 'resource_version': '2.0', 'event_type': 'CHECKOUT.ORDER.APPROVED', 'summary': 'An order has been approved by buyer', 'resource': {'update_time': '2022-12-19T18:57:02Z', 'create_time': '2022-12-19T18:56:51Z', 'purchase_units': [{'reference_id': 'default', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'payee': {'email_address': 'mailto:sb-dgfcl23459178#business.example.com', 'merchant_id': ''jkdshfhsjdfhjksfhjsfs'}, 'custom_id': 'e-book-1234', 'shipping': {'name': {'full_name': 'John Doe'}, 'address': {'address_line_1': '1 Main St', 'admin_area_2': 'San Jose', 'admin_area_1': 'CA', 'postal_code': '95131', 'country_code': 'US'}}, 'payments': {'captures': [{'id': '9HW93194EE464044X', 'status': 'COMPLETED', 'amount': {'currency_code': 'USD', 'value': '10.00'}, 'final_capture': True, 'seller_protection': {'status': 'ELIGIBLE', 'dispute_categories': ['ITEM_NOT_RECEIVED', 'UNAUTHORIZED_TRANSACTION']}, 'seller_receivable_breakdown': {'gross_amount': {'currency_code': 'USD', 'value': '10.00'}, 'paypal_fee': {'currency_code': 'USD', 'value': '0.84'}, 'net_amount': {'currency_code': 'USD', 'value': '9.16'}}, 'links': [{'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v2/payments/captures/9HW93194EE464044X/refund', 'rel': 'refund', 'method': 'POST'}, {'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'up', 'method': 'GET'}], 'create_time': '2022-12-19T18:57:02Z', 'update_time': '2022-12-19T18:57:02Z'}]}}], 'links': [{'href': 'https://api.sandbox.paypal.com/v2/checkout/orders/4CV868937U646315D', 'rel': 'self', 'method': 'GET'}], 'id': '4CV868937U646315D', 'payment_source': {'paypal': {}},
'intent': 'CAPTURE', 'payer': {'name': {'given_name': 'John', 'surname': 'Doe'},
'email_address': "adsfhjasdfhdajhk#gmail.com"
'payer_id': 'CSNQVZ49MMDA2',
'address': {'country_code': 'US'}},
'status': 'COMPLETED'},
'links': [{'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G', 'rel': 'self', 'method': 'GET'}, {'href': 'https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-65K55150EC946744T-1T312384BP483891G/resend', 'rel': 'resend', 'method': 'POST'}]}
Is there any inbuilt library which can handle this response in python or database design to handle this or I need to create it myself.

if statement in python airtable records - json

this are 3 records from airtable
I want to make a for loop in python (if value in 'check' is Update2 - do something, else do something else)
{'createdTime': '2022-11-09T15:57:28.000Z',
'fields': {'Last Modified': '2022-11-10T00:22:31.000Z',
'Name': 'Daniel',
'Status': 'Todo',
'check': 'update2'},
'id': 'recbvBuBBrgWO98pZ'}
{'createdTime': '2022-11-09T16:58:15.000Z',
'fields': {'Last Modified': '2022-11-10T00:22:32.000Z',
'Name': 'CLaudia',
'Status': 'In progress',
'check': 'update2'},
'id': 'reck3BB7lOVKG0cPI'}
{'createdTime': '2022-11-09T15:57:28.000Z',
'fields': {'Last Modified': '2022-11-10T00:22:32.000Z',
'Name': 'Isabella',
'Status': 'Done',
'check': 'update2'},
'id': 'recveGd8w9ukxLkk9'}
if record['fields']['check'] == 'update2':
do something
else:
do something else

How to Iterate over a list of dictionary and print dict if certain key has required value

As you can see below variable y contains a list of dictionaries which contain various details about a few persons,
I want to print the dictionary which contains the key named position = 'Account Manager'.
P.S: I'm pretty new to Python.
y = [{'email': 'hgibson#journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Hannah', 'lastName': 'Gibson', 'position': 'Corporate Flight Attendant'},
{'email': 'ncucalon#journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Nicole', 'lastName': 'Cucalon', 'position': 'Account Manager'},
{'email': 'shazamy#journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Sam', 'lastName': 'Hazamy', 'position': 'Maintenance Controller and Invoicing Specialist'},
{'email': 'rafaelbajares#journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Rafael', 'lastName': 'Bajares', 'position': 'Gulfstream IV Pilot'}]
for i in y:
if i.keys.position = 'Account Manager'
print(i)
Output :
if i.keys() ='Account Manager':
^ SyntaxError: invalid syntax
Your solution seems to be reliant on using a dictionary that is converted to dotted format(like DotDict from Robot framework).
Usually, a dcitionary is read like this y['position'].
Anyway, this code should work for your requirement:
y = [{'email': 'hgibson#journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Hannah', 'lastName': 'Gibson', 'position': 'Corporate Flight Attendant'},
{'email': 'ncucalon#journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Nicole', 'lastName': 'Cucalon', 'position': 'Account Manager'},
{'email': 'shazamy#journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Sam', 'lastName': 'Hazamy', 'position': 'Maintenance Controller and Invoicing Specialist'},
{'email': 'rafaelbajares#journeyflight.com', 'type': 'prospect', 'status': 'verified', 'firstName': 'Rafael', 'lastName': 'Bajares', 'position': 'Gulfstream IV Pilot'}]
for person_dict in y:
if person_dict.get("position", "") == "Account Manager"
print person_dict

Parsing json string into dataframe

I have a nested json string as follows:
[{'id': 'tfghnbkivbgdcse',
'authorization': None,
'operation_type': 'in',
'card': {'type': 'debit',
'brand': 'mastercard',
'address': None,
'card_number': '123456XXXXXX7890',
'holder_name': 'aaaa bbbb’,
'expiration_year': '21',
'expiration_month': '11',
'bank_name': 'XXXXBANK',
'bank_code': '000'},
'status': 'failed',
'creation_date': '2018-06-30T23:59:16-05:00',
'error_message': 'Bank authorization is required for this charge',
'order_id': '1743790',
'amount': 2668.0,
'currency': 'USD',
'customer': {'name': 'AAAA',
'last_name': 'BBBB',
'email': 'XXXX_1234#outlook.com',
'phone_number': '1234567890',
'address': None,
'creation_date': '2018-06-30T23:59:17-05:00',
'external_id': None,
'clabe': None},
'fee': {'amount': 0.95, 'tax': 0.152, 'currency': 'USD'}}]
I want to convert json string into data frame. I have used json_normalize from pandas.io.json, but I am getting an error.
It works if you:
Change all None to "None"
Change 'aaaa bbbb’ to 'aaaa bbbb' (The last character was a different single quote character)
Change all <'> to <">
It's probably just the quote character you need to fix, if the json data is part of python code.
In [39]: ord("'")
Out[39]: 39
In [40]: ord("’")
Out[40]: 8217

Unable to parse required data from nested arrays in json using python

When I tried with my script, I do get response but can't parse the Name and Email from this response as I never worked with json arrays. Hope there is somebody to give me an idea. I tried with:
import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
print(j)
And the partial response is like:
[{'EmailAddress': '', 'Zip': '', 'Members': [{'Fax': '', 'FirstLastName': 'Ryley Reat', 'Id': 46648, 'FirstName': 'Ryley', 'FullName': 'Ryley Reat', 'Email': 'zolo#zolo.ca', 'LastName': 'Reat', 'LocationId': 46647, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': '', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': 'CANADA', 'GeoCode': {'latitude': 56.130366, 'longitude': -106.346771}, 'City': '', 'FullAddress': 'CANADA', 'Id': 46647, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Zolo Realty Inc.', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': '', 'Zip': 'T3H 4W2', 'Members': [{'Fax': '', 'FirstLastName': 'David SandBrand', 'Id': 46646, 'FirstName': 'David', 'FullName': 'David SandBrand', 'Email': 'david#sandbrand.com', 'LastName': 'SandBrand', 'LocationId': 46645, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': 'AB', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': '146 West Springs Pl SW Calgary, AB T3H 4W2 CANADA', 'GeoCode': {'latitude': 51.0626195, 'longitude': -114.1907432}, 'City': 'Calgary', 'FullAddress': '146 West Springs Pl SW Calgary, AB T3H 4W2 CANADA', 'Id': 46645, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Damecca Holdings Ltd', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': 'c.reception#century21.ca', 'Zip': 'S9V 0N7', 'Members': [{'Fax': '', 'FirstLastName': 'Alex Palmer', 'Id': 45347, 'FirstName': 'Alex', 'FullName': 'Alex Palmer', 'Email': 'alex.palmer#century21.ca', 'LastName': 'Palmer', 'LocationId': 37526, 'Phone': '(306) 821-0138', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Becky Hofer', 'Id': 45379, 'FirstName': 'Becky', 'FullName': 'Becky Hofer', 'Email': 'becky.hofer#century21.ca', 'LastName': 'Hofer', 'LocationId': 37526, 'Phone': '(306) 830-9740', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Cheryl Fairweather', 'Id': 45346, 'FirstName': 'Cheryl', 'FullName': 'Cheryl Fairweather', 'Email': 'cheryl.fariweather#century21.ca', 'LastName': 'Fairweather', 'LocationId': 37526, 'Phone': '(780) 808-9406', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Chris Hassall', 'Id': 45334, 'FirstName': 'Chris', 'FullName': 'Chris Hassall', 'Email': 'chris.hassall#century21.ca', 'LastName': 'Hassall', 'LocationId': 37526, 'Phone': '(780) 871-3838', 'WebSite': ''}
Write before the print(j)
import pdb; pdb.set_trace()
Run your script and then the console will wait for commands, there you can write commands, start playing with your json, remember that a Json are tuples with dictionaries, that can have more tupels or more dictionaries inside, so you will end with something like
print (j[1]['EmailAddress'])
Finally found the solution:
import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
for item in j:
print(item['Members'][0]['FirstLastName'],item['Members'][0]['Email'], item['Members'][0]['Phone'])

Categories