繁体   English   中英

将嵌套字典转换为元组 python

[英]Convert Nested dictionaries to tuples python

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

以下是词典

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',))]

我期待以下 output 而没有提到字典的第一个键

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

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

>>> 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)]

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

>>> 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')]
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM