Home > OS >  How to merge two Dictionary in python with same key but different value
How to merge two Dictionary in python with same key but different value

Time:11-01

I want to merge multiple dictionary in python with the same keys

Dictionary

[
{
'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'
}
]

I am expecting

Output

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

Can Anyone help me to achieve the above answer

CodePudding user response:

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
  • Related