List inside a list - how to access an element - python

This is my code:
def liveGame(summonerName):
req = requests.get('https://br1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/' + str(summonerName) + '?api_key=' + apikey)
req_args = json.loads(req.text)
print(req_args)
And this is what I'm receiving from my request.get:
{
'gameId': 1149933395,
'mapId': 11,
'participants': [
{
'teamId': 100,
'spell1Id': 11,
'spell2Id': 4,
'championId': 141,
'profileIconId': 7,
'summonerName': 'Disneyland Party',
...
}
]
}
I've simplified the return of the request, but as you can see the 'participants' index is another list. So, how can I access the contents of this list (teamId, Spell1Id, etc)?
I can only access the full list this way:
print(req_args['participants'])
But, what I want to do is access only one element of the 'participants' list.
I'm using Python 3.6.

You can access this list items using index as you do for normal list
If you want to access first element for req_args['participants'] you can use
req_args['participants'][i]
where i is nothing but the index of item that you want to access from list.
Since items inside linked list are dictionaries to access teamId and spellId of only one item ( in this case first item) you can do following
req_args['participants'][0]['teamId']
req_args['participants'][0]['spell1Id']
you can also iterate over list to access each dictionary and value of teamId, spell1Id or others keys present inside dictionary like this
for participant in req_args['participants']:
print(participant['teamId'])
print(participant['spell1Id'])

this is simple to get value from dictionary object.
print items['participants'][0].get('teamId')
print items['participants'][0].get('spell1Id')

Related

Find a specific key in python dictionary inside a list

I have a list of dictionaries and I am looking to get a specific key at a certain index
[
{
"id":"23fr3yf48",
"type":"engine",
"details":{
"text":"New",
"type":"SPT_2048",
"id":"7033_Q-156",
"engine_details":{
"dateCreated":"2021-08-13 08:59:32.870953+00:00",
"createdBy":"John",
},
},
"confirm":true
},
{
"id":"3u823983hf",
"type":"wheel",
"details":{
"text":"Old",
"type":"SPT_0006",
"id":"101841_2004497"
},
"confirm":true
},
]
In this JSON I want to get the 'id' inside 'details' dict. I specifically want to get the 'details' from the index 1 that has id - '101841_2004497' skipping the 0th index. I want to know to iterate through the list and find the specific index. Can someone help me with this?
This is a simple for loop to check each item in list if the id of its details is equal to the value which you mentioned: 101841_2004497
for item in list:
if item["details"]["id"] == "101841_2004497":
print(item["details"])
JSON response:
{'text': 'Old', 'type': 'SPT_0006', 'id': '101841_2004497'}
Hope it helps!
You don't need to iterate through the list - you can directly access an item by its index. See, for example the Python tutorial.

Difficulty understanding changes to dictionary

I was looking through old posts in order to find a method of changing values in a dictionary by iterating through the items.
dictionary = {
1: [
{
"id": "1234",
"cow": "parts/sizes/lakes"
},
{
"id": "5151",
"cow": "minors/parts"
}
]}
def fetchanswers():
for item in dictionary[1]:
yield(item["id"], item["cow"])
for a, b in fetchanswers():
k = {}
k["id"] = a
k["cow"] = b.replace("parts", a)
My understanding is that yield returns the two items from either object in the dictionary and the for loop creates a new dictionary and appends the values obtained from fetchanswers() and parts is replaced by id.
I don't understand how k["id"] can be referred to when the dictionary is empty.
a method of changing values in a dictionary
Your values are strings. Strings are immutable, so you need to overwrite the dictionary using existing keys
You don't need another dictionary for this
# replace "parts" text value with the value of the id key
for item in list_of_dicts:
item["cow"] = item["cow"].replace("parts", str(item["id"]))
how k["id"] can be referred to
It's not a referral when there's an equal sign afterwards. It's an assignment

Getting an dict by name with in a list with an element key within a variable

data = {
"items" : [{"potion" : 1}, {"potion2" : 1}]
}
print(data["items"][0]["potion"])
So, here's the jiz. I want to get potion2 without providing number like [0] but i can't because some variables has 5 items within the list while another one might have 3 items so providing a number might not giving me what i need. Is there a way to get potion2 without providing that number before it?
I'm assuming you don't want to provide the index because hard coding it will not work in all circumstances.
You can just pull out any items in the list which have that key.
Build a list of any items, which have that key. It might ordinarily be just one, but the container itself does not enforce that only one entry can have that key.
After that you can either iterate over the list or check if the returned value is empty and just take the first element.
>>> data = {'items': [{'potion': 1}, {'potion2': 1}]}
>>> e = filter(lambda i: 'potion' in i, data['items'])
>>> for i in e:
... print(i['potion'])
...
1
Or to pull out only the first element. I realize you said no indices, but this index is applied to the filtered list and we check that its not empty first, so it's a valid thing to do.
>>> if e:
... print(e[0]['potion'])
...
1

python nested lists/dictionaries and popping values

Apologies in advance for this being such a newbie question. I'm just beginning to write python and i've been having some confusion around popping values from nested dictionaries/lists so i appreciate any help!
I have this sample json data:
{ "scans": [
{ "status": "completed", "starttime": "20150803T000000", "id":533},
{ "status": "completed", "starttime": "20150803T000000", "id":539}
] }
i'd like to pop the 'id' out of the "scans" key.
def listscans():
response = requests.get(scansurl + "scans", headers=headers, verify=False)
json_data = json.loads(response.text)
print json.dumps(json_data['scans']['id'], indent=2)
doesnt seem to be working because the nested key/values are inside of a list. i.e.
>>> print json.dumps(json_data['scans']['id'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
can anyone point me in the right direction to get this to work? my longterm goal with this is to create a for-loop that places all of the id's into another dictionary or list that i can use for another function.
json_data['scans'] returns a list of dicts, you are trying to index the list using a str i.e []["id"] which fails for obvious reasons so you need to use the index to get each subelement:
print json_data['scans'][0]['id'] # -> first dict
print json_data['scans'][1]['id'] # -> second dict
Or to see all the id's iterate over the list of dicts returned using json_data["scans"]:
for dct in json_data["scans"]:
print(dct["id"])
To save append to a list:
all_ids = []
for dct in json_data["scans"]:
all_ids.append(dct["id"])
Or use a list comp:
all_ids = [dct["id"] for dct in json_data["scans"]]
If there is a chance the key id might not be in every dict, use in to check before you access:
all_ids = [dct["id"] for dct in json_data["scans"] if "id" in dct]
Here how can you iterate over the items and extract all ids:
json_data = ...
ids = []
for scan in json_data['scans']:
id = scan.pop('id')
# you can use get instead of pop
# then your initial data would not be changed,
# but you'll still have the ids
# id = scan.get('id')
ids.append();
This approach will work too:
ids = [item.pop('id') for item in json_data['scans']]

Appending something to a list within a dict within a list in Python

I am attempting to create a list of dicts which will have the following structure:
[
{
'id': '234nj233nkj2k4n52',
'embedded_list': []
},
{
'id': 'jb234bhj23423h4b4',
'embedded_list': []
},
...
]
Initially, this list will be empty.
What I need to be able to do is:
Check to see if a dict with a specific id exists in the list already
If a dict containing that id exists, append something to it's embedded_list
If a dict containing that id does not exist, create a dict, append it to the list.
I am aware of being able to test if a dict exists in a list based on something inside that dict using something like this:
extracted_dict = next((item for item in list if item['id'] == unique_id), None)
I am unsure of how to append something to a list within a dict within a list efficiently. Is there an obvious way which I'm not seeing (probably)?
Thank you in advance.
Your data structure should be a dictionary of dictionaries in the first place:
{'234nj233nkj2k4n52': {'embedded_list': []},
'jb234bhj23423h4b4': {'embedded_list': []},
... }
This will make all your desired operations much easier. If the inner dictionaries only contain the embedded list, this can be further simplified to
{'234nj233nkj2k4n52': [],
'jb234bhj23423h4b4': [],
... }
Now, all you need is a collections.defaultdict(list):
from collections import defaultdict
d = defaultdict(list)
d['234nj233nkj2k4n52'].append(whatever)
or just a simple dic
{
'234nj233nkj2k4n52' : [],
'jb234bhj23423h4b4' : []
}

Categories