I have a json array that looks like this:
{'1': {'ID': '1', ' ': 'Aaron K###', 'Distributor': 'National Energy', 'State': 'BC', 'Brand': 'Trane', 'Cell': '778-###-####', 'email address': '', 'Notes': '', '': ''}, '2': {'ID': '2', ' ': 'Martin', 'Distributor': 'Pierce Phelps', 'State': 'PA', 'Brand': 'Bryant/Carrier', 'Cell': '267-###-####', 'email address': '', 'Notes': '', '': ''},...
and I wanted to reconfigure it so that it matched django's serialization format.
I wrote this function to do it:
def re_serialize_reg_json():
d = load_file()
for i in d:
d[i]['Name'] = d[i][' ']
d[i]['pk'] = d[i]['ID']
d[i]['model'] = 'homepage.territorymanager'
d[i]['fields'] = {
'Name' : d[i]['Name'],
'Cell' : d[i]['Cell'],
'Email Address' : d[i]['email address'],
'Notes' : d[i]['Notes'],
'Distributor' : d[i]['Distributor'],
'State' :d[i]['State'],
'Brand' :d[i]['Brand'],
}
del d[i][' ']
del d[i]['ID']
del d[i]['Name']
del d[i]['Cell']
del d[i]['email address']
del d[i]['Notes']
del d[i]['Distributor']
del d[i]['State']
del d[i]['Brand']
del d[i]['']
and it works fine:
output:
{'1': {'pk': '1', 'model': 'homepage.territorymanager', 'fields': {'Name': 'Aaron Kirkus', 'Cell': '778-875-4983', 'Email Address': '', 'Notes': '', 'Distributor': 'National Energy', 'State': 'BC', 'Brand': 'Trane'}}, '2': {'pk': '2', 'model': 'homepage.territorymanager', 'fields': {'Name': 'Aaron Martin ', 'Cell': '267-246-0522', 'Email Address': '', 'Notes': '', 'Distributor': 'Pierce Phelps', 'State': 'PA', 'Brand': 'Bryant/Carrier'}},...
But I feel like it's not a very effective method for achieving this. Any ideas appreciated.
A list to store some keys, and some loop, would make the code a lot nicer
def re_serialize_reg_json(d):
for key, values in d.items():
values.update({'Name': values[' '], 'pk': values['ID'], 'model': 'homepage.territorymanager'})
f = ['Name', 'Cell', 'email address', 'Notes', 'Distributor', 'State', 'Brand']
values['fields'] = {' '.join(w.capitalize() for w in k.split()): values[k] for k in f}
for k in f + [' ', '', 'ID']:
del values[k]
return d
Related
I have a text file with the following column names. I want these to be the keys in my dictionary, and grab the value data from separating lines in the txt file, which contains a series of lines like such:
VLAN1100 84:03:28:a8:b3:18 D - ge-0/0/45.0 0 0 10.68.8.189:
key_list = ['vlan name', 'mac address', 'mac flags', 'age', 'logical interface', 'nh index', 'rtr id', 'IP']
with open('prog-input.txt', 'r') as file:
lines = file.readlines()`
#separate column data into lines
for line in lines:
if 'VLAN' in line:
#skip headers
entry = line.split()
res = {}
for key in key_list:
for value in entry:
res[key] = value
entry.remove(value)
break
print(res)
file.close()
This is correctly splitting the data into key value pairs, but not assigning them to individual dictionaries.
OUTPUT:
{'vlan name': 'VLAN1100', 'mac address': '94:40:c9:3a:44:1a', 'mac flags': 'D', 'age': '-', 'logical interface': 'ge-0/0/16.0', 'nh index': '0', 'rtr id': '0', 'IP': '10.68.14.67'}
{'vlan name': 'VLAN1100', 'mac address': '94:40:c9:3a:91:b6', 'mac flags': 'D', 'age': '-', 'logical interface': 'ge-0/0/8.0', 'nh index': '0', 'rtr id': '0', 'IP': '10.68.14.59'}
{'vlan name': 'VLAN1100', 'mac address': '94:40:c9:3a:e5:b2', 'mac flags': 'D', 'age': '-', 'logical interface': 'ge-0/0/17.0', 'nh index': '0', 'rtr id': '0', 'IP': '10.68.14.68'}
{'vlan name': 'VLAN1100', 'mac address': 'f4:a7:39:9c:4c:e0', 'mac flags': 'D', 'age': '-', 'logical interface': 'ge-0/0/47.0', 'nh index': '0', 'rtr id': '0', 'IP': '10.68.8.191'}`
I only care about the key:value pairs of 0, 1, 4, 7. I would like to assign each line entry with an ID, possibly based on the 'mac address', which is unique.
I also tried using this code, but I don't understand how to use map, so I'd rather it be spelled out:
if 'VLAN' in line:
device = {k:v for k, *v in map(line.split, file)}
for key in key_list:
for value in device:
device.append()
print(device)
But it doesn't work. I want to be able to create a dictionary for each line item, and then put them inside a List, to query later.
Here is a slightly generalised method, that only uses built-ins, which you can use to perform similar tasks to the one you have specified.
import operator
def split_lines_to_dicts(lines, column_map, line_filter, id_generator):
value_getter = operator.itemgetter(*list(column_map.keys()))
column_names = list(column_map.values())
return [
dict(
zip(column_names, value_getter(line.split())),
id=next(id_generator)
)
for line in lines
if line_filter(line)
]
To show how you might use that I'll show it with details plugged in from your situation:
import io
import itertools
print(split_lines_to_dicts(
# You would use a file handle here
lines=io.StringIO("""
# Ignore me
VLAN1100 84:03:28:a8:b3:18 D - ge-0/0/45.0 0 0 10.68.8.189
VLAN1100 84:03:28:a8:b3:18 D - ge-0/0/45.0 0 0 10.68.8.189
VLAN1100 84:03:28:a8:b3:18 D - ge-0/0/45.0 0 0 10.68.8.189
...
"""),
# The position to the name we want in the output
column_map={
0: "vlan name",
1: "mac address",
4: "logical interface",
7: "IP"
},
# A filter to decide which lines to keep
line_filter=lambda line: "VLAN" in line,
# A generator of ids, you could change this to do something else
id_generator=itertools.count()
))
This would give you a list like this:
[
{'vlan name': 'VLAN1100', 'mac address': '84:03:28:a8:b3:18', 'logical interface': 'ge-0/0/45.0', 'IP': '10.68.8.189', 'id': 0},
{'vlan name': 'VLAN1100', 'mac address': '84:03:28:a8:b3:18', 'logical interface': 'ge-0/0/45.0', 'IP': '10.68.8.189', 'id': 1},
{'vlan name': 'VLAN1100', 'mac address': '84:03:28:a8:b3:18', 'logical interface': 'ge-0/0/45.0', 'IP': '10.68.8.189', 'id': 2}
]
import io
import csv
import pandas as pd
file_content="""
VLAN1100 94:40:c9:3a:44:1a D - ge-0/0/16.0 0 0 10.68.14.67
VLAN1100 94:40:c9:3a:91:b6 D - ge-0/0/8.0 0 0 10.68.14.59
VLAN1100 94:40:c9:3a:e5:b2 D - ge-0/0/17.0 0 0 10.68.14.68
VLAN1100 f4:a7:39:9c:4c:e0 D - ge-0/0/47.0 0 0 10.68.8.191
"""
key_list = ['vlan name', 'mac address', 'mac flags', 'age',
'logical interface', 'nh index', 'rtr id', 'IP']
# with open("csv.abc") as fobj: #
# records = csv.DictReader(fobj, fieldnames=key_list, delimiter="\t")
file_buffer = io.StringIO(file_content)
records = csv.DictReader(file_buffer, fieldnames=key_list, delimiter="\t")
df = pd.DataFrame(records)
df = df.iloc[:, [0,1,4,7]]
df.to_dict("records")
[{'vlan name': 'VLAN1100',
'mac address': '94:40:c9:3a:44:1a',
'logical interface': 'ge-0/0/16.0',
'IP': '10.68.14.67'},
{'vlan name': 'VLAN1100',
'mac address': '94:40:c9:3a:91:b6',
'logical interface': 'ge-0/0/8.0',
'IP': '10.68.14.59'},
{'vlan name': 'VLAN1100',
'mac address': '94:40:c9:3a:e5:b2',
'logical interface': 'ge-0/0/17.0',
'IP': '10.68.14.68'},
{'vlan name': 'VLAN1100',
'mac address': 'f4:a7:39:9c:4c:e0',
'logical interface': 'ge-0/0/47.0',
'IP': '10.68.8.191'}]
Here's an example for what I am looking for. My previous code if I wanted to sort by last name:
from operator import getitem
main_dict = {}
main_dict['Kevin'] = {'ID': '1', 'Last Name': 'Jones', 'First Name': 'Kevin'}
main_dict['David'] = {'ID': '2', 'Last Name': 'Walker', 'First Name': 'David'}
sorted_lastname = sorted(main_dict.items(), key=lambda x: getitem(x[1], 'Last Name'))
print(sorted_lastname)
How can I sort this without the use of Lambda and itemgetter?
This is how to implement #buran's idea.
def func(tup):
key, d = tup
return d['Last Name']
main_dict = {}
main_dict['Kevin'] = {'ID': '1', 'Last Name': 'Jones', 'First Name': 'Kevin'}
main_dict['David'] = {'ID': '2', 'Last Name': 'Walker', 'First Name': 'David'}
sorted_lastname = sorted(main_dict.items(), key=func)
print(sorted_lastname)
Use normal function
main_dict = {}
main_dict['Kevin'] = {'ID': '1', 'Last Name': 'Jones', 'First Name': 'Kevin'}
main_dict['David'] = {'ID': '2', 'Last Name': 'Walker', 'First Name': 'David'}
def func(item):
return item[1]['Last Name']
sorted_lastname = sorted(main_dict.items(), key=func)
print(sorted_lastname)
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.
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'])
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.