How to flatten the value (list of lists of tuples) of a key in Python dictionary?

Viewed 450

I have a dictionary in python that looks like this:

   {(-1, 1): (0, 1),
   (0, 0): [([([(1, 0), (0, 1)], (0, 1))], (1, 0))],
   (0, 1): [([([((-1, 1), (0, 2))], (1, 1))], (0, 0))],
   (0, 2): (0, 1)} 

I don't want it to have all those extra brackets and parentheses. This is the code I used to create this dictionary:

      if condition1==True:
        if condition2==True:

           if (x,y) in adjList_dict:  ##if the (x,y) tuple key is already in the dict

               ##add tuple neighbours[i] to existing list of tuples 
               adjList_dict[(x,y)]=[(adjList_dict[(x,y)],neighbours[i])] 

                    else:
                        adjList_dict.update( {(x,y) : neighbours[i]} )

I am just trying to create a dictionary where the keys are tuples and the value of each key is a list of tuples.

For example I want this result: (0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)]

Can I flatten the output or should I change something in the creation of the dictionary?

2 Answers

You can use recursion and then test if the instance is a simple tuple with int values in it, for example:

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


def flatten(data, output):
    if isinstance(data, tuple) and isinstance(data[0], int):
        output.append(data)
    else:
        for e in data:
            flatten(e, output)


output = {}
for key, values in sample.items():
    flatten_values = []
    flatten(values, flatten_values)
    output[key] = flatten_values

print(output)
>>> {(-1, 1): [(0, 1)], (0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)], (0, 1): [(-1, 1), (0, 2), (1, 1), (0, 0)], (0, 2): [(0, 1)]}

you could use a recursive approach with dictionary comprehension:

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



def flatten(e):
    if isinstance(e[0], int):
        yield e
    else:    
        for i in e:
            yield from flatten(i)

{k: list(flatten(v)) for k, v in d.items()}

output:

{(-1, 1): [(0, 1)],
 (0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)],
 (0, 1): [(-1, 1), (0, 2), (1, 1), (0, 0)],
 (0, 2): [(0, 1)]}
Related