How to create a list of dictionaries from a dictionary

时间:2017-04-09 23:23:20

标签: python

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?

4 个答案:

答案 0 :(得分:2)

Sure, you can do it using a list comprehension like:

[{'attendance': a, 'date': d} for d, a in my_dict.items()]

答案 1 :(得分:2)

You can use list comprehension to create the dictionaries using:

my_list_dict = [{'attendance': v, 'data': k} for k,v in my_dict.items()]

答案 2 :(得分:2)

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()]

答案 3 :(得分:1)

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)