【问题标题】:How to merge two Dictionary in python with same key but different value如何在python中合并两个具有相同键但不同值的字典
【发布时间】:2021-12-15 14:40:40
【问题描述】:

我想在 python 中用相同的键合并多个字典

字典

[
{
'Question__questions': 'What is Python?',
'option': 'Front-end Language',
'imagesOptions': '',
'is_correct_answer': 'False'
}, 
{
'Question__questions': 'What is Python?',
'option': 'Backend-end Language',
'imagesOptions': '',
'is_correct_answer': 'True'
}, 
{
'Question__questions': 'What is Python?',
'option': 'Both',
'imagesOptions': '',
'is_correct_answer': 'False'
}, 
{
'Question__questions': 'What is Python?',
'option': 'None',
'imagesOptions': '',
'is_correct_answer': 'False'
}
]

我期待

输出

[
{
  'Question__questions': 'What is Python?',
  'option': ['Front-end Language','Backend-end Language','Both','None']
  'imagesOptions': '',
  'is_correct_answer': ['False','True','False', 'False']
}
]

谁能帮我实现上述答案

【问题讨论】:

    标签: json python-3.x list dictionary


    【解决方案1】:
    def merge(dicts):
        res = []
    
        for key in set(dict['Question__questions'] for dict in dicts):
            res.append({'Question__questions': key, 'option': [],
                       'imagesOptions': [], 'is_correct_answer': []})
    
        for d in dicts:
            for r in res:
                if d['Question__questions'] == r['Question__questions']:
                    r['option'].append(d['option'])
                    r['imagesOptions'].append(d['imagesOptions'])
                    r['is_correct_answer'].append(d['is_correct_answer'])
    
        return res
    

    【讨论】:

    • 非常感谢@simmondvt。它对我有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2017-04-20
    • 2018-08-02
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多