[英]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:我有 2 个 dict 列表:
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.您不能在 python 中组合/合并 2 个字典列表,但您可以创建一个新字典,其中
lst2
内容作为键, lst1
内容作为值。
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'
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.