简体   繁体   中英

Generate a specific dictionary structure from list in python

Hello i have list L given below

L=[(), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]

And i want to generate a specific dict type as given below from the list. I want to create a lattice of graph by passing the values of dict3 as input to graph in networkx python, and so need to create a dict where each tuple's value is all elements with length 1 greater than the length of the tuple.

dict3={(): [(0,), (1,), (2,)], (0,): [(0, 1), (0, 2), (1, 2)],
       (1,): [(0, 1), (0, 2), (1, 2)],(2,): [(0, 1), (0, 2), (1, 2)],(0, 1): [(0, 1, 2)], 
       (0, 2): [(0, 1, 2)],(1, 2): [(0, 1, 2)]}

Any suggestions how to do it?

You are looking for something like this:

D = {}
for x in L:
    D[x] = []
    for i in L:     
        if len(x) == len(i) -1:    
            D[x].append(i)

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