pythonlistdictionary

Pythonic way to flatten a dictionary into a list using list comprehension


I have the following function:

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.

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.

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?


Solution

  • You can do it like this:

    fields = ("field1", "field2", "field3")
    
    output = [[k] + [mydict[k].get(x) for x in fields] for k in mydict]
    

    In that code we iterate dict keys and add them with selected subset of second-level dictionaries values.