如何在Python字典中展平键的值(元组列表)?

如何在Python字典中展平键的值(元组列表)?,python,dictionary,tuples,nested-lists,flatten,Python,Dictionary,Tuples,Nested Lists,Flatten,我有一本python字典,看起来像这样: {(-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)} 我不希望它有所有额外的括号和括号。 这是我用来创建此词典的代码: if condition1==True: if conditi

我有一本python字典,看起来像这样:

   {(-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)} 
我不希望它有所有额外的括号和括号。 这是我用来创建此词典的代码:

      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]} )
我只是想创建一个字典,其中键是元组,每个键的值是元组列表

例如,我想要这个结果:
(0,0):[(1,0)、(0,1)、(0,1)、(1,0)]


我可以展平输出还是应该在创建字典时更改某些内容?

您可以使用递归,然后测试实例是否是一个包含int值的简单元组,例如:

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展平(数据、输出):
如果isinstance(数据,元组)和isinstance(数据[0],int):
output.append(数据)
其他:
对于数据中的e:
展平(e,输出)
输出={}
对于键,sample.items()中的值:
展平_值=[]
展平(值,展平\u值)
输出[键]=展平\u值
打印(输出)
>>> {(-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)]}

您可以使用字典理解的递归方法:

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()}
输出:

{(-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)]}