【问题标题】:Python: How to group dictionaries based on a key value pairPython:如何根据键值对对字典进行分组
【发布时间】:2014-06-29 14:25:12
【问题描述】:

假设我有一个 Python 字典列表,其中包含这种格式的音频元数据:

metadata = {'title': meta['title'][0],
            'artist': meta['artist'][0],
            'album': meta['album'][0],
            'path': path}

有什么方法可以遍历这些字典的列表,将唯一的 artist 字段连接到单个 artists 字段中,基于 album 字段,但保留其中一个路径?

例如,翻这些字典:

m1 = {'title': 'Song 1', 'artist': 'Artist 1', 'Album': 'Album 1', 'Path': 'path 1'}
m2 = {'title': 'Song 2', 'artist': 'Artist 1 Ft 2', 'Album': 'Album 1', 'Path': 'path 2'}
m3 = {'title': 'Song 3', 'artist': 'Artist 1 Ft 3', 'Album': 'Album 1', 'Path': 'path 3'}

进入这个:

m4 = {'artist': 'Artist 1; Artist 1 Ft 2; Artist 1 Ft 3', 'Album': 'Album 1', 'Path': 'path 1'}

这背后的原因是我想从文件列表(由字典表示)中创建专辑及其艺术家的列表,但我需要保留从中获取专辑插图的路径之一。

到目前为止,我已经尝试将所有数据添加到 MySQL 数据库中,在 image 列中包含专辑插图的 BLOB,并运行 SQL 命令:

CREATE TABLE albums SELECT album, image, GROUP_CONCAT(DISTINCT artist SEPARATOR '; ') AS artists FROM tracks GROUP BY album

然后从轨道的主数据库中删除图像列,但是这确实是资源密集型的,并且在构建它时占用了数据库中许多不必要的空间,所以理想情况下我需要一些方法来处理原始数据首先在 Python 中。

编辑:我忘了说,在字典列表中,会有多个专辑。我需要最终结果是一个字典列表,每个字典都包含一个唯一的专辑和与该专辑对应的所有艺术家标签的串联列表。

【问题讨论】:

  • 有一种方法.. 对于那些思考的人。坚持
  • 标题怎么样?
  • @thefourtheye 我不需要这些,所有的曲目标题都保存在数据库中,我可以使用专辑标题查找标题。
  • 好吧,如果出现不同的专辑?最终结果会是怎样的?
  • @alKid 我想创建一个包含所有独特专辑的列表,其中包含艺术家的串联列表,会有多个专辑。我将编辑我的问题以包含它,我应该提到这一点。

标签: python mysql database list dictionary


【解决方案1】:
m = [
    {'title': 'Song 1', 'artist': 'Artist 1',
        'Album': 'Album 1', 'Path': 'path 1'},
    {'title': 'Song 2', 'artist': 'Artist 1 Ft 2',
        'Album': 'Album 1', 'Path': 'path 2'},
    {'title': 'Song 3', 'artist': 'Artist 1 Ft 3',
        'Album': 'Album 1', 'Path': 'path 3'}
]

from collections import defaultdict

# Group all the artists, as per the Album name
d = defaultdict(list)
for item in m:
    d[item["Album"]].append(item["artist"])

# Gather paths corresponding to the Albums
p = {item["Album"]: item["Path"] for item in m}

# Recreate a list of all albums with artist names joined
result = []
for album in d:
    result.append({
        "Album" : album,
        "artist": "; ".join(d[album]),
        "Path"  : p[album]
    })

print result

【讨论】:

  • 我一定是变得迟钝了.. 好答案!
猜你喜欢
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
相关资源
最近更新 更多