根据字典值将字典转换为字典列表

时间:2011-07-11 11:44:29

标签: python list dictionary

我有不同的词典,我想重新组合成一个词典列表,考虑到它们的不同价值:

字典:

[{'language': 'de', 'suggestion': 'fressen', 'comment': 'for animals'},
{'language': 'de', 'suggestion': 'essen', 'comment': ''},
{'language': 'fr', 'suggestion': 'manger', 'comment': ''},
{'language': 'fr', 'suggestion': 'bouffer', 'comment': 'slang'}]

词典列表:

[{'language': 'de', 'suggestion': ['fressen', 'essen'], 'comment': ['for animals', '']}, \
{'language': 'fr', 'suggestion': ['manger', 'bouffer'], 'comment': ['', 'slang'}]

我仍然是一个蟒蛇初学者,我不知道从哪里开始,用相同的'语言'对所有词典进行分组:'de'到同一个词典。

4 个答案:

答案 0 :(得分:4)

一个直截了当的解决方案,假设所有dicts的键都相同:

ld = [{'language': 'de', 'suggestion': 'fressen', 'comment': 'for animals'},
{'language': 'de', 'suggestion': 'essen', 'comment': ''},
{'language': 'fr', 'suggestion': 'manger', 'comment': ''},
{'language': 'fr', 'suggestion': 'bouffer', 'comment': 'slang'}]

langs = {i['language'] for i in ld}

d = []

for lang in langs:
    d.append({"language": lang})
    for key in ld[0].keys() - ["language"]:
        d[-1][key] = [i[key] for i in ld if i["language"] == lang]

print(d)

输出:

[{'comment': ['', 'slang'],
  'language': 'fr',
  'suggestion': ['manger', 'bouffer']},
 {'comment': ['for animals', ''],
  'language': 'de',
  'suggestion': ['fressen', 'essen']}]

如果你选择使用他对你的问题的评论中描述的@ FMc的数据结构,你可以使用那个长的单行,用嵌套的理解来做所有事情:

d = {lang: 
        {i["suggestion"]: i["comment"]
        for i in ld if i["language"] == lang} 
    for lang in {i["language"] for i in ld}}

print(d)

输出:

{'de': {'essen': '', 'fressen': 'for animals'},
 'fr': {'bouffer': 'slang', 'manger': ''}}

答案 1 :(得分:1)

有点复杂的解决方案,但是:

>>> dicts = [{'language': 'de', 'suggestion': 'fressen', 'comment': 'for animals'},
... {'language': 'de', 'suggestion': 'essen', 'comment': ''},
... {'language': 'fr', 'suggestion': 'manger', 'comment': ''},
... {'language': 'fr', 'suggestion': 'bouffer', 'comment': 'slang'}]
>>> main_key = 'language'
>>> result_dict = dict()
>>> for d in dicts:
...     for key, value in d.iteritems():
...             if key == main_key:
...                     result_dict.setdefault(d[main_key], dict())[main_key] = value
...             else:
...                     result_dict.setdefault(d[main_key], dict()).setdefault(key, list()).append(value)
...
>>> result_dict.values()
[{'comment': ['', 'slang'], 'language': 'fr', 'suggestion': ['manger', 'bouffer']}, {'comment': ['for animals', ''], 'language': 'de', 'suggestion': ['fressen', 'essen']}]

基于main_key值,我们会加入此键列表中的所有其他词典。

答案 2 :(得分:1)

使用reduce可以清楚地分离合并和合并逻辑:

#!/usr/bin/env python

from pprint import pprint
from collections import defaultdict

def group(grouped, ungrouped):
    group = grouped[ungrouped['language']]
    group['language'] = ungrouped['language']
    group['suggestion'].append(ungrouped['suggestion'])
    group['comment'].append(ungrouped['comment'])
    return grouped

ungrouped = [{'language': 'de', 'suggestion': 'fressen', 'comment': 'for animals'},
             {'language': 'de', 'suggestion': 'essen', 'comment': ''},
             {'language': 'fr', 'suggestion': 'manger', 'comment': ''},
             {'language': 'fr', 'suggestion': 'bouffer', 'comment': 'slang'}]

grouped = reduce(group, ungrouped, defaultdict(lambda: defaultdict(list))).values()

# Convert defaultdict to dict for pretty printing.
pprint([dict(group) for group in grouped])

答案 3 :(得分:1)

不是非常pythonic但它也有效:

data = [{'language': 'de', 'suggestion': 'fressen', 'comment': 'for animals'},
{'language': 'de', 'suggestion': 'essen', 'comment': ''},
{'language': 'fr', 'suggestion': 'manger', 'comment': ''},
{'language': 'fr', 'suggestion': 'bouffer', 'comment': 'slang'}]

def prepare(inputData):
    outputData = []
    if inputData and isinstance(inputData[0], dict) and inputData[0].get('language'):
        keys = inputData[0].keys()
        del keys[keys.index('language')]
    else:
        #do something - raise issue or return
        return outputData 
    for l in set(line['language'] for line in inputData):
        langData = {"language": l}
        langData.update([(k, [line[k] for line in inputData if line["language"] == l]) for k in keys])
        outputData.append(langData)
    return outputData

prepare(data)