Python:如何基于键值对对字典进行分组

Python:如何基于键值对对字典进行分组,python,mysql,database,list,dictionary,Python,Mysql,Database,List,Dictionary,假设我有一个Python字典列表,其中包含以下格式的音频元数据: metadata = {'title': meta['title'][0], 'artist': meta['artist'][0], 'album': meta['album'][0], 'path': path} 是否有任何方法可以迭代这些字典的列表,根据相册字段将唯一的艺术家字段连接到单个艺术家字段中,但保留其中一个路径 例如,打开这些词典: m1 =

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

metadata = {'title': meta['title'][0],
            'artist': meta['artist'][0],
            'album': meta['album'][0],
            'path': path}
是否有任何方法可以迭代这些字典的列表,根据
相册
字段将唯一的
艺术家
字段连接到单个
艺术家
字段中,但保留其中一个路径

例如,打开这些词典:

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
列中添加一块相册插图,并运行SQL命令:

CREATE TABLE albums SELECT album, image, GROUP_CONCAT(DISTINCT artist SEPARATOR '; ') AS artists FROM tracks GROUP BY album
然后从轨道的主数据库中删除image列,但是这实际上是资源密集型的,并且在构建数据库时会占用数据库中大量不必要的空间,因此理想情况下,我需要先用Python中的原始数据来完成这项工作


编辑:我忘了提到,在字典列表中,将有多个相册。我需要的最终结果是一个字典列表,每个字典都包含一个唯一的相册,以及与该相册对应的所有艺术家标签的串联列表。

有一种方法。。对于那些有想法的人。等等,标题呢?@thefortheye我不需要这些,所有的曲目标题都保存在一个数据库中,我可以使用专辑标题查找标题。如果出现不同的专辑?最终的结果会是什么样?@alKid我想创建一个包含所有独特专辑的列表,其中包含艺术家的串联列表,将有多张专辑。我会修改我的问题,把它包括进去,我应该提到这一点的。我一定是变得迟钝了。。回答得好!
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