Reputation: 43
Let's say I have this dict for example
my_dict = {'10/31/2016': 66.49746192893402, '11/14/2016': 63.95939086294417,
'08/29/2016': 77.15736040609137}
Is it possible to turn that dictionary into a list of dictionaries so it would look like this.
my_list_dict = [{'attendance': 66.49746192893402, 'date': '10/31/2016'},
{'attendance': 63.95939086294417, 'date': '11/14/2016'},
{'attendance': 77.15736040609137, 'date': '08/29/2016'}]
What would the code for this look like?
Upvotes: 2
Views: 85
Reputation: 2236
A more verbose example with explicit iteration rather than a comprehension. I'd use the comprehension though this might be easier to understand.
my_dict = {'10/31/2016': 66.49746192893402, '11/14/2016': 63.95939086294417,
'08/29/2016': 77.15736040609137}
x = []
for item in my_dict:
new_dict = {'attendance': my_dict[item], 'date': item}
x.append(new_dict)
print(x)
Upvotes: 1
Reputation: 25997
A simple list comprehension can do this for you:
[{'attendance': v, 'date': k} for k, v in my_dict.items()]
This gives you the desired output:
[{'attendance': 63.95939086294417, 'date': '11/14/2016'},
{'attendance': 77.15736040609137, 'date': '08/29/2016'},
{'attendance': 66.49746192893402, 'date': '10/31/2016'}]
In Python2 you can also use iteritems
which will give you a speed-up for huge dictionaries:
[{'attendance': v, 'date': k} for k, v in my_dict.iteritems()]
Upvotes: 2
Reputation: 36608
You can use list comprehension to create the dictionaries using:
my_list_dict = [{'attendance': v, 'data': k} for k,v in my_dict.items()]
Upvotes: 2
Reputation: 992917
Sure, you can do it using a list comprehension like:
[{'attendance': a, 'date': d} for d, a in my_dict.items()]
Upvotes: 2