简体   繁体   中英

Combine two list of dict to one dict by adding value of one list of dict as key to another

I have 2 list of dict as:

lst1= [{'st_name': 'ram', 'st_email_id': 'ram@abc.com'}, {'st_name': 'Raj', 'st_email_id': 'raj@abc.com'}, {'st_name': 'jatin', 'st_email_id': 'jatin@abc.com'},{'st_name': 'tom', 'st_email_id': 'tom@abc.com'}]

lst2 = [{'team_name': 'Team1'}, {'team_name': 'Team2'}]

want something like this:

{
"team1":
[
    {
        'st_name': 'ram', 
        'st_email_id': 'ram@abc.com',
     
    },
    {
        'st_name': 'Raj',
        'st_email_id': 'raj@abc.com'
    }
],
"team2":
[
    {
        'st_name': 'jatin',
        'st_email_id': 'jatin@abc.com'
    },
    {
        'st_name': 'tom',
        'st_email_id': 'tom@abc.com'
    }
]
}  

(without considering how do you know who belongs to which team)

you can't combine/merge togheter 2 list of dictionaries in python, but you can create a new dictionary with lst2 content as the keys and lst1 content as the values.

note: my result isn't the same as what you requested, because is up to you what values you actually need inside the dictonary.

with that being said, the code i pretty simple:

lst1 = #dict_list with the values
lst2 = #dict_list with the keys

dict_final = {}
for key in lst2:
        dict_final[key['team_name']] = lst1 #<- lst1 should be replaced by your needs

print(dict_final)

final result:

{
    'Team1':
    [
        {
            'st_name': 'ram',
            'st_email_id': 'ram@abc.com'
        }, 
        {
            'st_name': 'Raj',
            'st_email_id': 'raj@abc.com'
        }, 
        {
            'st_name': 'jatin', 
            'st_email_id': 'jatin@abc.com'
        }, 
        {
            'st_name': 'tom', 
            'st_email_id': 'tom@abc.com'
        }
    ],
    'Team2': 
    [
        {
            'st_name': 'ram', 
            'st_email_id': 'ram@abc.com'
        },
        {
            'st_name': 'Raj',
            'st_email_id': 'raj@abc.com'
        }, 
        {
            'st_name': 'jatin', 
            'st_email_id': 'jatin@abc.com'
        },
        {
            'st_name': 'tom', 
            'st_email_id': 'tom@abc.com'
        }
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM