Search code examples
pythonpython-3.xdictionarydictionary-comprehension

Convert dictionary to new key:value pairs in a list of dicts


I´ve seen several questions in this matter, but haven´t been able to find a solutions to adapt in my case. I got a one level dictionary with several key:value pairs, in which the keys are names and the values are always numerical (float), like the following:

dict = {'keyname1':0.44,'keyname2':1.23,'keyname3':0.76}

And I need to create a list of dicts with two key:value pairs, like:

new_dict_list  = [{'name':'keyname1', 'time':0.44},{'name':'keyname2', 'time':1.23},{'name':'keyname3', 'time':0.76}]

Solution

  • This is as simple as continuously making a dictionary with those values. We can use dict.items() to iterate through the items (key value pair).

    new_dict_list = [
        {'name': name, 'time': time}
        for name, time in dict.items()
    ]