switch key and values in a dict of lists

前端 未结 3 480
孤街浪徒
孤街浪徒 2021-01-26 18:50

Hello Stackoverflow people,

I have a nested dictionary with lists as values and I want to create a dict where all the list entries get their corresponding key as value.<

3条回答
  •  孤街浪徒
    2021-01-26 19:17

    Try this

    dict1 = {"A":[1,2,3], "B":[4,5,6], "C":[7,8,9]}
    dict2= {}
    for keys,values in dict1.items():
        for i in values:
            dict2[i]=keys
    print(dict2)
    

    Output

    {1: 'A', 2: 'A', 3: 'A', 4: 'B', 5: 'B', 6: 'B', 7: 'C', 8: 'C', 9: 'C'}
    

    Hope it helps

提交回复
热议问题