Search lists inside dictionaries from API request - python

I'm trying to query a dictionary with a list and another dictionary inside. I'm using the deck of cards API and want to pull the value out.
drawCard='https://deckofcardsapi.com/api/deck/vx58tedq5moe/draw/?count=1'
response = requests.get(drawCard)
getValue = json.loads(response.text)
value= (getValue['cards'])
print (getValue)
print("")
print("")
print (value)
card= (getValue['cards'](''))
This is what I get when I print getValue.
{'deck_id': 'vx58tedq5moe', 'success': True, 'cards': [{'suit': 'SPADES', 'code': '0S', 'value': '10', 'images': {'png': 'https://deckofcardsapi.com/static/img/0S.png', 'svg': 'https://deckofcardsapi.com/static/img/0S.svg'}, 'image': 'https://deckofcardsapi.com/static/img/0S.png'}], 'remaining': 44}
I narrowed it down to this using getValue['cards'] but cant go any further.
[{'suit': 'SPADES', 'code': '0S', 'value': '10', 'images': {'png': 'https://deckofcardsapi.com/static/img/0S.png', 'svg': 'https://deckofcardsapi.com/static/img/0S.svg'}, 'image': 'https://deckofcardsapi.com/static/img/0S.png'}]
I want to grab the 10 from value

The value of getValue['cards'] is a list, so first you want to access the list element, getValue['cards'][0] then you can access the element 'value' with
getValue['cards'][0]['value']
If you want to get all value from all cards in the list of cards, you can use list comprehension to do something like
[c['value'] for c in getValue['cards']]

You go multiple levels down like this:
value= (getValue['cards']['value'])
BC 'cards' is the key to the list and 'value' is key to the value in the list witch have the value of 10.

Related

I want to get the randomly picked key value from the dictionaries list but I got a type error.(note the list is long so putting a index is difficult)

def data_change(account):
data_name = data["name"]
data_desc = data["description"]
data_country = data["country"]
return f"{data_name}, is a {data_desc}, from {data_country}"
print(f"option A : {data_change(data_a)}")
The above code is data I want to process for the random data to display.
the list dictionary below are the first 2 example data
data = [
{
'name': 'Instagram',
'follower_count': 346,
'description': 'Social media platform',
'country': 'United States'
},
{
'name': 'Cristiano Ronaldo',
'follower_count': 215,
'description': 'Footballer',
'country': 'Portugal'
}]
and the error display is
TypeError: list indices must be integers or slices, not str
on the line: data_name = data["name"]
yes, I searched for numerous solutions but it didn't get my problem solved.
like from this link
https://www.learndatasci.com/solutions/python-typeerror-list-indices-must-be-integers-or-slices-not-str/#:~:text=This%20type%20error%20occurs%20when,using%20the%20int()%20function.
if u want to want the full file for the code ask me ok. it is a work in progress
Data is a list and not a dictionary so you use zero based index to enumerate the items in the list. You could enumerate the items via a for loop like this:
def data_change(data):
ans = []
for account in data:
data_name = account["name"]
data_desc = account["description"]
data_country = account["country"]
ans.append(f"{data_name}, is a {data_desc}, from {data_country}")
return "\n".join(ans)
Your variable data is a list with two dictionaries in it.
With data_name = data["name"] you try to access this list but name is not an integer, so you get the TypeError.
Your list only has two entries, so you can access it with data[0]["name"] or data[1]["name"].
Edit: Iterating over the dicts in your list as Mazimia stated, seems like a good idea.

Python Accessing a Value in a List of Dictionaries, if another Value in the Dictionary Exists

My question is an extension to this:
Python Accessing Values in A List of Dictionaries
I want to only return values from dictionaries if another given value exists in that dictionary.
In the case of the example given in the linked question, say I only want to return 'Name' values if the 'Age' value in the dictionary is '17'.
This should output
'Suzy'
only.
result = [d["Name"] for d in dicts if d.get("Age") == 17)]
Of course this would select all nanes that satisfy the condition. You can put that in a function.
In the following case :
listname= [
{'Name': 'Albert' , 'Age': 16},
{'Name': 'Suzy', 'Age': 17},
{'Name': 'Johnny', 'Age': 13}
]
If you want return only people Name when "age == 17" use :
for d in listname:
if d['Age'] == 17 :
print (d['Name'])
Use a condition inside your for.
Edit 10/01/2022 : Change "list" to "listname", cause list il already reserved in python.

Searching List of non-standardized Dictionaries

I scraped a betting website API. Scraping this API returned JSON in what is essentially a list of dictionaries. I am trying to search through this list of dictionaries and return specific bets and odds. Below is my code:
Team1 = 'Lechia Gdańsk'
Team2 = 'Sokół Ostróda'
WDW = [{'id': 2853153615, 'label': '1', 'englishLabel': '1', 'odds': 1250, 'participant': 'Lechia Gdańsk', 'type': 'OT_ONE', 'betOfferId': 2244628386, 'changedDate': '2021-01-14T18:52:07Z', 'participantId': 1000020086, 'oddsFractional': '1/4', 'oddsAmerican': '-400', 'status': 'OPEN', 'cashOutStatus': 'ENABLED'}, {'id': 2853153626, 'label': 'X', 'englishLabel': 'X', 'odds': 5750, 'type': 'OT_CROSS', 'betOfferId': 2244628386, 'changedDate': '2021-01-14T18:52:07Z', 'oddsFractional': '19/4', 'oddsAmerican': '475', 'status': 'OPEN', 'cashOutStatus': 'ENABLED'}, {'id': 2853153638, 'label': '2', 'englishLabel': '2', 'odds': 7000, 'participant': 'Sokół Ostróda', 'type': 'OT_TWO', 'betOfferId': 2244628386, 'changedDate': '2021-01-14T18:52:07Z', 'participantId': 1001302448, 'oddsFractional': '6/1', 'oddsAmerican': '600', 'status': 'OPEN', 'cashOutStatus': 'ENABLED'}]
unisoccerWDWTeam1 = next((item['odds']/1000 for item in WDW if item['participant'] == Team1), None)
unisoccerWDWTeam2 = next((item['odds']/1000 for item in WDW if item['participant'] == Team2), None)
unisoccerWDWDraw = next((item['odds']/1000 for item in WDW if item['label'] == 'X'), None)
I use next() and dictionary comprehension to search for a matching team name and then return the odds from the list of dictionaries. The issue is the dictionaries are not uniform within the list and so when my code encounters a dictionary without the key I'm searching for it returns an error. In this case WDW[1] does not have 'participant' in the dictionary. Is there a way to avoid this problem or skip dictionaries that do not contain the Key:Value pair I am searching for? I am considering simply writing nested for loops maybe with try except blocks to avoid this however this seems like a slow and inelegant solution. Any suggestions or help would be much appreciated.
To simply avoid the exception, you can use item.get('participant'), which will return None if "participant" doesn't exist, rather than raising an exception. (Which is similar to the None default you are using for you next call.
Depending on how you implement the loop, this should allow you to silently skip dictionaries that don't contain the keys you are looking for.
This would be something like:
unisoccerWDWTeam1 = next((item['odds']/1000 for item in WDW if item.get('participant') == Team1), None)
Code not tested, but should get you started.

Python efficiently getting a specific value from a list of dictionaries

I am using an API to get results from a database that is returned in JSON format. I'm then trying to just extract certain keys/values and append them to a blank list. The field I want is eissn and the API returns results like this:
[
{'type': 'doi', 'id': '10.16472/j.chinatobacco.2017.045'},
{'type': 'pissn', 'id': '1004-5708'},
{'type': 'eissn', 'id': '1004-5708'}
]
I want to extract the eissn id which i have tried using this code:
deissnlist = []
for i in range(0,lengthD):
deissnlist.append(doajresult[i]['bibjson']['identifier'][3]
['id'])
Where lengthD/i are the number of results returned from the API. The problem is that the eissn ID is not always the 3rd dictionary in the list. Is there any way I can search the tuples and only get the eissn ID without using another for loop (and thus going from O(n) to O(n^2)? The expected output is just the single value of the eissn id (in this case 1004-5708)
I tried converting the list to a dictionary but that didn't work because it treated each tuple as it's own dictionary. Thanks!
I may have misunderstood question and over simplified; but, if you are looking to simply extract a list of the ids from that sample input, this is how I would do it:
input = [
{'type': 'doi', 'id': '10.16472/j.chinatobacco.2017.045'},
{'type': 'pissn', 'id': '1004-5708'},
{'type': 'eissn', 'id': '1004-5708'}
]
result = [x.get('id') for x in input]
print(result)
['10.16472/j.chinatobacco.2017.045', '1004-5708', '1004-5708']
Or for just the ids where type is eissn:
result = [x.get('id') for x in input if x.get('type') == 'eissn']

JSON: iterate over a list of nested dictionaries

I have a huge list of dictionaries appended to the list from JSON in the manner below. I would like to access the "raw" from each dictionary and store it entire in a list of dictionary or a one huge dictionary. The final goal is to access the keys in the raw and convert them to dataframe columns using pandas.
results = [{
'FirstSentences': None,
'PrintableUri': '',
'hasHtmlVersion': False,
'hasMobileHtmlVersion': False,
'isRecommendation': False,
'isTopResult': False,
'parentResult': None,
'percentScore': 100.0,
'printableUriHighlights': [],
'rankingInfo': None,
'rating': 3.0,
'raw': {'distance': 1892760.0,
'distancekm': 1892.76,
'distancemi': 1176.11,
'objecttype': 'Account',
'objecttypename': 'Account',
'plocepp': 'False',
'plochpp': 'False',
'plocsdp': 'False'}}]
The code and the error I'm getting is as below:
response = [x['raw'] for x in results]
File "<ipython-input-90-64993f9dcd67>", line 1, in <module>
response = [x['raw'] for x in results]
TypeError: list indices must be integers, not str
I have searched a lot of answers here but couldn't find the solution to my problem. Thanks a lot for the help in advance.
The key is to iterate through the list and for each element in the list, index the dictionary key 'raw'.
One simple way is to iterate over the list and and access the key 'raw' in the dictionary.
Simple for loop method:
response = []
for d in results:
response.append(d['raw'])
List comprehension method
response = [d['raw'] for d in results]

Categories

Resources