簡體   English   中英

通過將一個 dict 列表的值作為鍵添加到另一個 dict 將兩個 dict 列表組合到一個 dict

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

我有 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'}]

想要這樣的東西:

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

(不考慮你怎么知道誰屬於哪個團隊)

您不能在 python 中組合/合並 2 個字典列表,但您可以創建一個新字典,其中lst2內容作為鍵, lst1內容作為值。

注意:我的結果與您要求的不同,因為您在字典中實際需要的值取決於您。

話雖如此,代碼很簡單:

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)

最后結果:

{
    '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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM