How to iterate over nested dictionaries in a LIST, using for loop

Hi there,
I would like to extract the second key of every dictionary using a for loop. However, the dictionaries are nested in a list (see below). Also, notice that the second key is not always the same (this is where I am struggling).

video_Ids = [
{'kind': 'youtube#playlist',
  'playlistId': 'PLt1O6njsCRR-D_1jUAhJrrDZyYL6OZSGa'},
 {'kind': 'youtube#playlist',
  'playlistId': 'PLt1O6njsCRR_8oi7E6qnPWGQbn8NoQ6sG'},
 {'kind': 'youtube#channel', 'channelId': 'UC4i5R6-IW05iiU8Vu__vppA'},
 {'kind': 'youtube#video', 'videoId': 'XquM0L2WUio'},
 {'kind': 'youtube#video', 'videoId': '05yrGVZ96b4'}
]

I have tried different things but none have worked, so far. Here is my last attempt: deleting the first key to be left with a list containing the second keys.

for i in video_Ids:
    if video_Ids["kind"] == "youtube#video":
        del video_Ids[i]["kind"]
    elif video_Ids[i]["kind"] == "youtube#playlist":
        del video_Ids[i]["kind"]
    elif video_Ids[i]["kind"] == "youtube#channel":
        del video_Ids[i]["kind"]

this is the message I get:

TypeError: list indices must be integers or slices, not str

I tried my best and got stuck on this for a few days now. I really appreciate any help, Thank you.

Hi @boemer00,

To extract the second key of every dictionary, please use the following code:

second_keys = []

for dictionary in video_Ids:
    second_keys.append(list(dictionary)[1])
    
print(second_keys)

Output:

['playlistId', 'playlistId', 'channelId', 'videoId', 'videoId']

Hi @Elena_Kosourova, thanks for your help.

Actually, I expressed myself poorly. My mistake, I do apologise. I would like to get the second value of each dictionary in that list.

I have just tried doing this and it did not work:

second_value = []

for key, value in len(range(video_Ids)):
    if key == "videoId":
        second_value.append(value)
    elif key == "playlistId":
        second_value.append(value)
    elif key == "channelId":
        second_value.append(value)

and got this:

TypeError: 'list' object cannot be interpreted as an integer

Could you please help me?

Thank you so much!

1 Like

Ah, ok, then you have to modify my code above in this way:

second_values = []

for dictionary in video_Ids:
    second_values.append(list(dictionary.values())[1])
    
print(second_values)

Output:

['PLt1O6njsCRR-D_1jUAhJrrDZyYL6OZSGa', 'PLt1O6njsCRR_8oi7E6qnPWGQbn8NoQ6sG', 'UC4i5R6-IW05iiU8Vu__vppA', 'XquM0L2WUio', '05yrGVZ96b4']
1 Like

Thank you so much!! :raised_hands:

1 Like

You are welcome @boemer00

1 Like