if statement in python airtable records - json - python

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

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.

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

Sort and return all of nested dictionaries based on specified key value

I am trying to re-arrange the contents of a nested dictionaries where it will check the value of a specified key.
dict_entries = {
'entries': {
'AzP746r3Nl': {
'uniqueID': 'AzP746r3Nl',
'index': 2,
'data': {'comment': 'First Plastique Mat.',
'created': '17/01/19 10:18',
'project': 'EMZ',
'name': 'plastique_varA',
'version': '1'},
'name': 'plastique_varA',
'text': 'plastique test',
'thumbnail': '/Desktop/mat/plastique_varA/plastique_varA.jpg',
'type': 'matEntry'
},
'Q2tch2xm6h': {
'uniqueID': 'Q2tch2xm6h',
'index': 0,
'data': {'comment': 'Camino from John Inds.',
'created': '03/01/19 12:08',
'project': 'EMZ',
'name': 'camino_H10a',
'version': '1'},
'name': 'camino_H10a',
'text': 'John Inds : Camino',
'thumbnail': '/Desktop/chips/camino_H10a/camino_H10a.jpg',
'type': 'ChipEntry'
},
'ZeqCFCmHqp': {
'uniqueID': 'ZeqCFCmHqp',
'index': 1,
'data': {'comment': 'Prototype Bleu.',
'created': '03/01/19 14:07',
'project': 'EMZ',
'name': 'bleu_P23y',
'version': '1'},
'name': 'bleu_P23y',
'text': 'Bleu : Prototype',
'thumbnail': '/Desktop/chips/bleu_P23y/bleu_P23y.jpg',
'type': 'ChipEntry'
}
}
}
In my above nested dictionary example, I am trying to check it by the name and created key (2 functions each) and once it has been sorted, the index value will be updated accordingly as well...
Even so, I am able to query for the values of the said key(s):
for item in dict_entries.get('entries').values():
#The key that I am targetting at
tar_key = item['name']
but this is returning me the value of the name key and I am unsure on my next step as I am trying to sort by the value of the name key and capturing + re-arranging all the contents of the nested dictionaries.
This is my desired output (if checking by name):
{'entries': {
'ZeqCFCmHqp': {
'uniqueID': 'ZeqCFCmHqp',
'index': 1,
'data': {'comment': 'Prototype Bleu.',
'created': '03/01/19 14:07',
'project': 'EMZ',
'name': 'bleu_P23y',
'version': '1'},
'name': 'bleu_P23y',
'text': 'Bleu : Prototype',
'thumbnail': '/Desktop/chips/bleu_P23y/bleu_P23y.jpg',
'type': 'ChipEntry'
}
'Q2tch2xm6h': {
'uniqueID': 'Q2tch2xm6h',
'index': 0,
'data': {'comment': 'Camino from John Inds.',
'created': '03/01/19 12:08',
'project': 'EMZ',
'name': 'camino_H10a',
'version': '1'},
'name': 'camino_H10a',
'text': 'John Inds : Camino',
'thumbnail': '/Desktop/chips/camino_H10a/camino_H10a.jpg',
'type': 'ChipEntry'
},
'AzP746r3Nl': {
'uniqueID': 'AzP746r3Nl',
'index': 2,
'data': {'comment': 'First Plastique Mat.',
'created': '17/01/19 10:18',
'project': 'EMZ',
'name': 'plastique_varA',
'version': '1'},
'name': 'plastique_varA',
'text': 'plastique test',
'thumbnail': '/Desktop/mat/plastique_varA/plastique_varA.jpg',
'type': 'matEntry'
}
}
}

Python parsing JSON nested data

I am trying to parse this JSON data from the setlist.fm api. I am trying to get all the song names in order from each setlist. I have looked around but none of the methods describe on the internet are working.
Here is the JSON data
{'itemsPerPage': 20,
'page': 1,
'setlist': [{'artist': {'disambiguation': '',
'mbid': 'cc197bad-dc9c-440d-a5b5-d52ba2e14234',
'name': 'Coldplay',
'sortName': 'Coldplay',
'tmid': 806431,
'url': 'https://www.setlist.fm/setlists/coldplay-3d6bde3.html'},
'eventDate': '15-11-2017',
'id': '33e0845d',
'info': 'Last show of the A Head Full of Dreams Tour',
'lastUpdated': '2017-11-23T14:51:05.000+0000',
'sets': {'set': [{'song': [{'cover': {'disambiguation': '',
'mbid': '9dee40b2-25ad-404c-9c9a-139feffd4b57',
'name': 'Maria Callas',
'sortName': 'Callas, Maria',
'url': 'https://www.setlist.fm/setlists/maria-callas-33d6706d.html'},
'name': 'O mio babbino caro',
'tape': True},
{'info': 'extended intro with Charlie '
'Chaplin speech',
'name': 'A Head Full of Dreams'},
{'name': 'Yellow'},
{'name': 'Every Teardrop Is a '
'Waterfall'},
{'name': 'The Scientist'},
{'info': 'with "Oceans" excerpt in '
'intro',
'name': 'God Put a Smile Upon Your '
'Face'},
{'info': 'with Tiësto Remix outro',
'name': 'Paradise'}]},
{'name': 'B-Stage',
'song': [{'name': 'Always in My Head'},
{'name': 'Magic'},
{'info': 'single version',
'name': 'Everglow'}]},
{'name': 'A-Stage',
'song': [{'info': 'with "Army of One" excerpt '
'in intro',
'name': 'Clocks'},
{'info': 'partial',
'name': 'Midnight'},
{'name': 'Charlie Brown'},
{'name': 'Hymn for the Weekend'},
{'info': 'with "Midnight" excerpt in '
'intro',
'name': 'Fix You'},
{'name': 'Viva la Vida'},
{'name': 'Adventure of a Lifetime'},
{'cover': {'disambiguation': '',
'mbid': '3f8a5e5b-c24b-4068-9f1c-afad8829e06b',
'name': 'Soda Stereo',
'sortName': 'Soda Stereo',
'tmid': 1138263,
'url': 'https://www.setlist.fm/setlists/soda-stereo-7bd6d204.html'},
'name': 'De música ligera'}]},
{'name': 'C-Stage',
'song': [{'info': 'extended',
'name': 'Kaleidoscope',
'tape': True},
{'info': 'acoustic',
'name': 'In My Place'},
{'name': 'Amor Argentina'}]},
{'name': 'A-Stage',
'song': [{'cover': {'mbid': '2c82c087-8300-488e-b1e4-0b02b789eb18',
'name': 'The Chainsmokers '
'& Coldplay',
'sortName': 'Chainsmokers, '
'The & '
'Coldplay',
'url': 'https://www.setlist.fm/setlists/the-chainsmokers-and-coldplay-33ce5029.html'},
'name': 'Something Just Like This'},
{'name': 'A Sky Full of Stars'},
{'info': 'Extended Outro; followed by '
'‘Believe In Love’ Tour '
'Conclusion Video',
'name': 'Up&Up'}]}]},
'tour': {'name': 'A Head Full of Dreams'},
'url': 'https://www.setlist.fm/setlist/coldplay/2017/estadio-ciudad-de-la-plata-la-plata-argentina-33e0845d.html',
'venue': {'city': {'coords': {'lat': -34.9313889,
'long': -57.9488889},
'country': {'code': 'AR', 'name': 'Argentina'},
'id': '3432043',
'name': 'La Plata',
'state': 'Buenos Aires',
'stateCode': '01'},
'id': '3d62153',
'name': 'Estadio Ciudad de La Plata',
'url': 'https://www.setlist.fm/venue/estadio-ciudad-de-la-plata-la-plata-argentina-3d62153.html'},
'versionId': '7b4ce6d0'},
{'artist': {'disambiguation': '',
'mbid': 'cc197bad-dc9c-440d-a5b5-d52ba2e14234',
'name': 'Coldplay',
'sortName': 'Coldplay',
'tmid': 806431,
'url': 'https://www.setlist.fm/setlists/coldplay-3d6bde3.html'},
'eventDate': '14-11-2017',
'id': '63e08ec7',
'info': '"Paradise", "Something Just Like This" and "De música '
'ligera" were soundchecked',
'lastUpdated': '2017-11-15T02:40:25.000+0000',
'sets': {'set': [{'song': [{'cover': {'disambiguation': '',
'mbid': '9dee40b2-25ad-404c-9c9a-139feffd4b57',
'name': 'Maria Callas',
'sortName': 'Callas, Maria',
'url': 'https://www.setlist.fm/setlists/maria-callas-33d6706d.html'},
'name': 'O mio babbino caro',
'tape': True},
{'info': 'extended intro with Charlie '
'Chaplin speech',
'name': 'A Head Full of Dreams'},
{'name': 'Yellow'},
{'name': 'Every Teardrop Is a '
'Waterfall'},
{'name': 'The Scientist'},
{'info': 'with "Oceans" excerpt in '
'intro',
'name': 'Birds'},
{'info': 'with Tiësto Remix outro',
'name': 'Paradise'}]},
{'name': 'B-Stage',
'song': [{'name': 'Always in My Head'},
{'name': 'Magic'},
{'info': 'single version; dedicated '
'to the Argentinian victims '
'of the New York terrorist '
'attack',
'name': 'Everglow'}]},
{'name': 'A-Stage',
'song': [{'info': 'with "Army of One" excerpt '
'in intro',
'name': 'Clocks'},
{'info': 'partial',
'name': 'Midnight'},
{'name': 'Charlie Brown'},
{'name': 'Hymn for the Weekend'},
{'info': 'with "Midnight" excerpt in '
'intro',
'name': 'Fix You'},
{'name': 'Viva la Vida'},
{'name': 'Adventure of a Lifetime'},
{'cover': {'disambiguation': '',
'mbid': '3f8a5e5b-c24b-4068-9f1c-afad8829e06b',
'name': 'Soda Stereo',
'sortName': 'Soda Stereo',
'tmid': 1138263,
'url': 'https://www.setlist.fm/setlists/soda-stereo-7bd6d204.html'},
'info': 'Coldplay debut',
'name': 'De música ligera'}]},
{'name': 'C-Stage',
'song': [{'info': 'Part 1: "The Guest House"',
'name': 'Kaleidoscope',
'tape': True},
{'info': 'acoustic; Will on lead '
'vocals',
'name': 'In My Place'},
{'info': 'song made for Argentina',
'name': 'Amor Argentina'},
{'info': 'Part 2: "Amazing Grace"',
'name': 'Kaleidoscope',
'tape': True}]},
{'name': 'A-Stage',
'song': [{'name': 'Life Is Beautiful'},
{'cover': {'mbid': '2c82c087-8300-488e-b1e4-0b02b789eb18',
'name': 'The Chainsmokers '
'& Coldplay',
'sortName': 'Chainsmokers, '
'The & '
'Coldplay',
'url': 'https://www.setlist.fm/setlists/the-chainsmokers-and-coldplay-33ce5029.html'},
'name': 'Something Just Like This'},
{'name': 'A Sky Full of Stars'},
{'name': 'Up&Up'}]}]},
This is part of the JSON I grabbed from the URL.
Below is the code I am trying touse:
import requests
import json
from pprint import*
url = "https://api.setlist.fm/rest/1.0/artist/cc197bad-dc9c-440d-a5b5-d52ba2e14234/setlists?p=1"
headers = {'x-api-key': 'API-KEY',
'Accept': 'application/json'}
r = requests.get(url, headers=headers)
data = json.loads(r.text)
#pprint(r.json())
response = data['setlist']
#pprint(response)
for item in response:
pprint(item['sets']['set']['song']['name'])
However I get this error that I cannot resolve nor find any help online with:
pprint(item['sets']['set']['song']['name'])
TypeError: list indices must be integers or slices, not str
Dictionaries (Dict) are accessed by keys.
Lists are accessed by indexes.
i.e.
# Dict get 'item'.
data = {'key': 'item'}
data['key']
# List get 'item0'.
data = ['item0', 'item1']
data[0]
# Dict with List get 'item0'.
data = {'key': ['item0', 'item1']}
data['key'][0]
Both storage types can be nested in JSON and either needs to be accessed in a
different manner.
You have nested Lists which need to be indexed through and that can be done by
a for loop.
I have no access to workable json data except for the Python incomplete object
that you show so I have not tested my code. Thus, no assurance that this
is correct. If not, it may demonstrate how to do the task.
import requests
import json
from pprint import *
url = "https://api.setlist.fm/rest/1.0/artist/cc197bad-dc9c-440d-a5b5-d52ba2e14234/setlists?p=1"
headers = {'x-api-key': 'API-KEY',
'Accept': 'application/json'}
r = requests.get(url, headers=headers)
data = json.loads(r.text)
result = []
for setlist_item in data['setlist']:
for set_item in setlist_item['sets']['set']:
for song_item in set_item['song']:
result += [song_item['name']]
print(result)
Each for loop is processing each list to finally get to extending the result with
each song name.

Setting a flag when the approval type equals 1 and no -1

I am trying to set a flag based on the approval type "TEST" when its value equals '1' but no "-1",am using the below but running into following error
flag = 'false'
ApprovalItem = [{'by': {'username': 'lnxbuild', 'name': 'Linux Build Service Account', 'email': 'lnxbuild#localhost'}, 'type': 'VRIF', 'description': 'Verified', 'value': '1', 'grantedOn': 1376515352}, {'by': {'username': 'c_ssugas', 'name': 'name', 'email': 'c_ssugas#company.com'}, 'type': 'TEST', 'description': 'Developer Verified', 'value': '-1', 'grantedOn': 1376532352}, {'by': {'username': 'ytkim', 'name': 'Ben Young Tae Kim', 'email': 'ytkim#company.com'}, 'type': 'CRVW', 'description': 'Code Review', 'value': '1', 'grantedOn': 1376514495}, {'by': {'username': 'ytkim', 'name': 'Ben Young Tae Kim', 'email': 'ytkim#company.com'}, 'type': 'TEST', 'description': 'Developer Verified', 'value': '1', 'grantedOn': 1376514495}]
if ApprovalItem['type'] == 'TEST' and ApprovalItem['description'] == 'Developer Verified' and ApprovalItem['value'] == '1' :
flag = True
print flag
Error:-
TypeError: list indices must be integers, not str
ApprovalItem is a list of dictionaries, not a dictionary itself.
>>> ApprovalItem = [{'by': {'username': 'lnxbuild', 'name': 'Linux Build Service Account', 'email': 'lnxbuild#localhost'}, 'type': 'VRIF', 'description': 'Verified', 'value': '1', 'grantedOn': 1376515352}, {'by': {'username': 'c_ssugas', 'name': 'name', 'email': 'c_ssugas#company.com'}, 'type': 'TEST', 'description': 'Developer Verified', 'value': '-1', 'grantedOn': 1376532352}, {'by': {'username': 'ytkim', 'name': 'Ben Young Tae Kim', 'email': 'ytkim#company.com'}, 'type': 'CRVW', 'description': 'Code Review', 'value': '1', 'grantedOn': 1376514495}, {'by': {'username': 'ytkim', 'name': 'Ben Young Tae Kim', 'email': 'ytkim#company.com'}, 'type': 'TEST', 'description': 'Developer Verified', 'value': '1', 'grantedOn': 1376514495}]
>>> print type(ApprovalItem)
<type 'list'>
>>> print type(ApprovalItem[0])
<type 'dict'>
You probably want a for-loop:
>>> for d in ApprovalItem:
... if d['type'] == 'TEST' and d['description'] == 'Developer Verified' and d['value'] == '1' :
... flag = True
... print flag
...
True
You are using list to store your several dict.
You can use for, I think, to check each dict.

Categories