python: tuple of dictionary to Dictionary

后端 未结 6 1858
一个人的身影
一个人的身影 2021-01-20 19:02

How can I convert tuple of dictionaries like example present below:

({(1, 2): 3},
 {(1, 3): 5},
 {(1, 4): 5},
 {(2, 4): 5},
 {(1, 5): 10},
 {(2, 6): 9},
 {(1         


        
6条回答
  •  野的像风
    2021-01-20 19:59

    just iterate on the tuples and rebuild the dictionary "flat" using a dictionary comprehension:

    a = ({(1, 2): 3},
     {(1, 3): 5},
     {(1, 4): 5},
     {(2, 4): 5},
     {(1, 5): 10},
     {(2, 6): 9},
     {(1, 6): 9},
     {(2, 1): 2},
     {(2, 2): 3},
     {(2, 3): 5},
     {(2, 5): 10},
     {(1, 1): 2})
    
    b = {k:v for t in a for k,v in t.items()}
    
    print(b)
    

    result:

    {(1, 2): 3, (2, 6): 9, (2, 1): 2, (1, 1): 2, (1, 5): 10, (1, 3): 5, (1, 6): 9, (1, 4): 5, (2, 2): 3, (2, 3): 5, (2, 5): 10, (2, 4): 5}
    

提交回复
热议问题