Python Forum

Full Version: Creating a list from a comprehension using a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
keyIDs = list(jsonData.keys())   #list of IDs
listOfValsFromKeys = students[keyIDs[i] for i in range(len(keyIDs))]    #list of names
When I run the lines above, I get a syntax error in between the 'for' and the 'i'. I cannot work out why this is the case. Could someone enlighten me?
It isn't clear what you're trying to accomplish. students[...] suggests slicing a sequence named "students", but you can't use a list comprehension for that. Please clarify the objective and the data types/structures at play.

Also, line two does not need range(len()). You can just use the iterable in Python.

for i in keyIDs:
    ...
(Sep-30-2019, 06:41 PM)stullis Wrote: [ -> ]It isn't clear what you're trying to accomplish. students[...] suggests slicing a sequence named "students", but you can't use a list comprehension for that. Please clarify the objective and the data types/structures at play.

Also, line two does not need range(len()). You can just use the iterable in Python.

for i in keyIDs:
    ...

Thanks, instead of 'students' I was meant to put 'jsonData'. I'm trying to do this with comprehensions instead of using for loops.
Trying to do what with comprehensions instead of loops. Replacing "students" with "jsonData" will still have the same error. What is the end goal?
(Sep-30-2019, 06:46 PM)stullis Wrote: [ -> ]Trying to do what with comprehensions instead of loops. Replacing "students" with "jsonData" will still have the same error. What is the end goal?

keyIDs = list(jsonData.keys())   #list of IDs
listOfValsFromKeys = jsonData[keyIDs[i] for i in range(len(keyIDs))]    #list of names
jsonData is a dictionary that has a key and properties linked to that key. I would like keyIDs to have the keys of the Json (which is working) and listOfValsFromKeys to have the properties linked to these keys. This code currently gives a sytax error but having looked at other examples of comprehensions, I can't see how a syntax error would be given.
Okay, now I'm tracking. To do that, we need to move jsonData into the comprehension.

keyIDs = list(jsonData.keys())   #list of IDs
listOfValsFromKeys = [jsonData[i] for i in keyIDs]
Of course, you could also use dict.values() instead. It performs the same operation as dict.keys() except it returns the values instead of keys.
(Sep-30-2019, 06:54 PM)stullis Wrote: [ -> ]Okay, now I'm tracking. To do that, we need to move jsonData into the comprehension.

keyIDs = list(jsonData.keys())   #list of IDs
listOfValsFromKeys = [jsonData[i] for i in keyIDs]
Of course, you could also use dict.values() instead. It performs the same operation as dict.keys() except it returns the values instead of keys.

Great thanks :)