Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need to use the index once you have the dictionary:

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

To extract the second key, you need to iterate on each dictionary. For example:

from itertools import islice
secondKeys = [ {k:v} for d in video_Ids for k,v in islice(d.items(),1,2)]

# or without itertools ...

secondKeys = [ {k:v} for d in video_Ids for _,(k,v),*_ in [d.items()]]
    
print(secondKeys)
[{'playlistId': 'PLt1O6njsCRR-D_1jUAhJrrDZyYL6OZSGa'},
 {'playlistId': 'PLt1O6njsCRR_8oi7E6qnPWGQbn8NoQ6sG'},
 {'channelId': 'UC4i5R6-IW05iiU8Vu__vppA'},
 {'videoId': 'XquM0L2WUio'},
 {'videoId': '05yrGVZ96b4'}]

or, if you only want the keys and not the corresponding values:

from itertools import islice
secondKeys = [ k for d in video_Ids for k in islice(d,1,2)]

# or without itertools ...

secondKeys = [ k for d in video_Ids for _,k,*_ in [d]]

print(secondKeys)
['playlistId', 'playlistId', 'channelId', 'videoId', 'videoId']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...