【问题标题】:creating a frequency dictionary from an existing dictionary从现有字典创建频率字典
【发布时间】:2019-11-26 15:41:59
【问题描述】:

我有一本名为 playlist 的字典,其条目形式为:

{datetime.datetime(2019, 11, 4, 20, 2): ('Wagon Wheel', 'Darius Rucker'), 
datetime.datetime(2019, 11, 4, 19, 59): ('Remember You Young', 'Thomas Rhett'), 
datetime.datetime(2019, 11, 4, 19, 55): ('Long Hot Summer', 'Keith Urban')}

我想遍历这个字典来构造一个新的字典 song_count,其中每首歌曲的名称作为键,其计数/频率作为值。到目前为止,这是我所拥有的代码。

song_count = {}
for song in playlist:
    if playlist[song] in song_count:
        song_count[playlist[song]].append(song)
    else:
        song_count[playlist_[song]]=[song]
print(song_count)

但是,这无法将歌曲与键中的艺术家分开,也不会将计数创建为值。

新字典应如下所示:

{'Wagon Wheel-Darius Rucker': 1, 
'Remember You Young-Thomas Rhett': 7, 
'Long Hot Summer-Keith Urban': 1, … }

【问题讨论】:

    标签: python python-3.x dictionary count python-datetime


    【解决方案1】:

    使用collections.Counter:

    import collections
    import datetime
    
    d = {datetime.datetime(2019, 11, 4, 20, 2): ('Wagon Wheel', 'Darius Rucker'), 
         datetime.datetime(2019, 11, 4, 19, 59): ('Remember You Young', 'Thomas Rhett'), 
         datetime.datetime(2019, 11, 4, 19, 55): ('Long Hot Summer', 'Keith Urban')}
    songs = ['-'.join(song) for song in d.values()]
    c = collections.Counter(songs)
    

    输出是:

    Counter({'Wagon Wheel-Darius Rucker': 1, 'Remember You Young-Thomas Rhett': 1, 'Long Hot Summer-Keith Urban': 1})
    

    【讨论】:

      【解决方案2】:

      尝试对您的代码进行这种改编:

      # Initialise new dictionary
      song_count = dict()
      
      # For each entry in the playlist dict
      for song in playlist.values():
          # Convert the tuple to song-artist string
          song_name = '-'.join(song)
      
          # If already in the dictionary, add 1 to the count
          if song_name in song_count:
              song_count[song_name] += 1
      
          # Otherwise set the count to 1
          else:
              song_count[song_name] = 1
      print(song_count)
      

      输出:

      {'Wagon Wheel-Darius Rucker': 1, 'Remember You Young-Thomas Rhett': 1, 'Long Hot Summer-Keith Urban': 1}
      

      【讨论】:

        猜你喜欢
        • 2016-04-15
        • 2014-12-18
        • 2017-06-24
        • 1970-01-01
        • 1970-01-01
        • 2017-04-14
        • 2019-11-17
        • 2014-10-02
        • 2016-11-20
        相关资源
        最近更新 更多