-3

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}]
Lucas Mengual
  • 263
  • 6
  • 21
  • 2
    Use a list comprehension, like `[{"name": key, "time": value} for key, value in dict.items()]` – kojiro Jun 16 '20 at 15:45

2 Answers2

2

Try this one please.

new_dict_list = [{'name': k, 'time': v} for k, v in dict.items()]
Perfect
  • 1,616
  • 1
  • 19
  • 27
1

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()
]
Peilonrayz
  • 3,129
  • 1
  • 25
  • 37