我该如何将所有这些综合起来?

时间:2019-10-02 03:51:04

标签: dictionary python-3.7 dictionary-comprehension

我很难理解字典理解。我有一些代码需要检查轨道是否已从iTunes资料库中删除。如果有的话,我需要将其从特定的播放列表字典以及主曲目字典中删除。

我尝试使用下面的代码,但是它告诉我字典的大小在迭代过程中发生了变化。

我在阅读herehere时试图理解我如何以字典理解的方式来完成所有这些工作,但这却使我的大脑融化了。

# Next step is to ensure the track_id for a particular persistent_id is correct
# because iTunes can change the track_id of a track, but the persistent_id
# remains the same regardless of any track changes.
#
# Step through each playlist in the musicDict dictionary and update the
# persistentID with the correct trackID or delete the track data from the
# dictionary if it cannot be found in the itl

for playlistKey in musicDict['playlists'].keys():
   if 'tracks' in musicDict['playlists'][playlistKey]:
      for persistentID in musicDict['playlists'][playlistKey]['tracks'].keys():
         try:
            musicDict['playlists'][playlistKey]['tracks'][persistentID] = itl.byPID[persistentID].track_id # Track exists in itl
         except:
            del musicDict['playlists'][playlistKey]['tracks'][persistentID] # track no longer exists in itl
         if persistentID in musicDict['tracks'].keys() and persistentID not in itl.byPID.keys(): # check to see if the track needs to be deleted from the musicDict
            del musicDict['tracks'][persistentID] # delete the track since it no longer exists in itl

我正在使用libpytunes模块,并添加了另一个名为byPID的字典,因为track_id对于iTu​​nes音乐不是保持静态,因此是persistentID变量和itl.byPID字典。

就像我在上面写的那样,这会产生一个错误(并且我理解为什么),并且我想将其转换为列表理解,或者如果理解不容易理解的话,可以将其转化为有效的for循环。

0 个答案:

没有答案