使用列表理解将字典平整为列表的Python方法 [英] Pythonic way to flatten a dictionary into a list using list comprehension
问题描述
我具有以下功能:
def create_list_from_dict1(mydict):
output = []
for k, v in openint_dict.items():
output.append( (k, v['field1'], v['field2'], v['field3']) )
return output
从本质上讲,它使字典变平,以便我可以对返回列表中元组的字段之一进行排序.
Essentially, it flattens the dictionary, so that I can perform sorting on one of the fields of the tuple in the returned list.
我不喜欢必须硬编码"值字典的字段名称('field1'
,...,'fieldN'
)的事实,而我想要一种更加Python化和优雅的方式这样做是为了使此函数适用于所有包含固定结构(非嵌套)字典作为其值的字典.
I don't like the fact that I am having to 'hard code' the field names of the value dictionary ('field1'
, ..., 'fieldN'
), and I want a more pythonic and elegant way of doing this so that this function works for all dictionaries that contain a fixed structure (non-nested) dictionary as its values.
我想我将不得不使用**kwargs
和/或lambda
函数,以及列表理解.编写此函数的最pythonic方法是什么?
I imagine that I will have to use **kwargs
and/or a lambda
function, as well as list comprehension. What would be the most pythonic way to write this function?
推荐答案
您可以这样做:
fields = ("field1", "field2", "field3")
output = [[k] + [mydict[k].get(x) for x in fields] for k in mydict]
在该代码中,我们迭代dict键,并将它们与第二级字典值的选定子集相加.
In that code we iterate dict keys and add them with selected subset of second-level dictionaries values.
这篇关于使用列表理解将字典平整为列表的Python方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!