拼合字典列表

时间:2020-10-08 02:53:30

标签: python-3.x list dictionary

我有一个包含键和值以及其他信息的字典列表,如下所示:

mylist  = [ {'key': 'captial' , 'value': 'captial of india'},
            {'key': 'captial' , 'value': 'captial of usa'},
            {'key': 'fruit' , 'value': 'colour of apple'},
            {'key': 'fruit' , 'value': 'colour of orange'}]

如何整理列表以获取以下输出

result=[{'title':'captial',questions:[{text:'captial of usa'},{text:'captial of india'}]},
        {'title':'fruit',questions:[{text:'colour of apple'},{text:'colour of orange'}]}]

2 个答案:

答案 0 :(得分:0)

您可以使用defaultdict和列表推导来获得结果。 defaultdict会将mylist中出现的 相同键 的值进行分组,然后将这些分组的值与自定义键一起使用(根据需要)在您的result中使用列表理解。

from collections import defaultdict

mylist = [...]

a_list = defaultdict(list)

for item in mylist:
    a_list[item["key"]].append(item["value"])

result = [
    {"title": key, "questions": [{"text": v} for v in value]}
    for key, value in a_list.items()
]

输出:

[
    {
        "title": "captial",
        "questions": [{"text": "captial of india"}, {"text": "captial of usa"}],
    },
    {
        "title": "fruit",
        "questions": [{"text": "colour of apple"}, {"text": "colour of orange"}],
    },
]

答案 1 :(得分:0)

这是一种有点复杂的格式,但是:

from collections import defaultdict

def groupby_key(xs, key, value):
    groups = defaultdict(list)
    for d in xs:
        groups[d[key]].append(d[value])
    return groups

def reformat(xs):
    groups = groupby_key(xs, "key", "value")
    return [
        {
            "title": k,
            "questions": [{"text": v} for v in vs],
        }
        for k, vs in groups.items()
    ]

用法:

>>> result = reformat(mylist)
>>> from pprint import pprint
>>> pprint(result, sort_dicts=False)
[{'title': 'captial',
  'questions': [{'text': 'captial of india'}, {'text': 'captial of usa'}]},
 {'title': 'fruit',
  'questions': [{'text': 'colour of apple'}, {'text': 'colour of orange'}]}]