将嵌套字典转换为元组 python

时间:2021-01-26 20:59:55

标签: python python-3.x

我想将嵌套字典转换为元组。我试过了,但没有得到预期的结果。我想在没有列表理解的情况下做到这一点

以下是字典

test_dict = {'Layer 4': {'start_2': '38.52', 'start_1': '35.15'}}

以下是我的代码

# printing original dictionary 
print("The original dictionary is : " + str(test_dict)) 
  
# Convert Nested dictionary to Mapped Tuple 
# Using list comprehension + generator expression 
res = [(key, tuple(sub[key] for sub in test_dict.values()))  
                               for key in test_dict['Layer 4']] 
  
# printing result  
print("The grouped dictionary : " + str(res)) 

我得到的结果

The original dictionary is : {'Layer 4': {'start_2': '38.52', 'start_1': '35.15'}}
The grouped dictionary : [('start_2', ('38.52',)), ('start_1', ('35.15',))]

而且我期待以下输出而不提及字典的第一个键

[('Layer 4', 'start_2','38.52'), ('Layer 4','start_1', '35.15')]

2 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。这是一个:

>>> d={'a':{'b':1,'c':2}}
>>> sum([ [ (k, *w) for w in v.items() ] for k, v in d.items() ], [])
[('a', 'b', 1), ('a', 'c', 2)]

答案 1 :(得分:0)

问题是你在元组内部和值上做一个理解,而不是在项目上做,第二级在那些项目上做

>>> test_dict = {'Layer 4': {'start_2': '38.52', 'start_1': '35.15'}}
>>> [ (key,*item) for key,value in test_dict.items() for item in value.items()]
[('Layer 4', 'start_2', '38.52'), ('Layer 4', 'start_1', '35.15')]
>>> 
>>> [ item for key,value in test_dict.items() for item in value.items()]
[('start_2', '38.52'), ('start_1', '35.15')]
>>> 

实际上,如果您不关心外部字典的键,则不需要项目

>>> [ item for value in test_dict.values() for item in value.items()]
[('start_2', '38.52'), ('start_1', '35.15')]
>>> 

有点深奥的方法

>>> list(*map(dict.items,test_dict.values()))
[('start_2', '38.52'), ('start_1', '35.15')]
>>> 

但是,如果例如我们在外部字典中有另一个键,那就不太有效

>>> test_dict2 = {'Layer 4': {'start_2': '38.52', 'start_1': '35.15'}, 'Layer 
23': {'start_23': '138.52', 'start_13': '135.15'}}
>>> [ item for value in test_dict2.values() for item in value.items()]
[('start_2', '38.52'), ('start_1', '35.15'), ('start_23', '138.52'), 
('start_13', '135.15')] 
>>>

为了以更深奥的方式获得相同的结果,我们可以使用 itertools

>>> import itertools
>>> list(itertools.chain.from_iterable(map(dict.items,test_dict2.values())))
[('start_2', '38.52'), ('start_1', '35.15'), ('start_23', '138.52'), 
('start_13', '135.15')]
>>> 
相关问题