简体   繁体   English

如何从字典中创建字典列表

[英]How to create a list of dictionaries from a dictionary

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? 代码会是什么样的?

当然,你可以使用列表理解来做到这一点:

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

您可以使用列表推导来创建字典:

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

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: 在Python2中,您还可以使用iteritems ,它将为您提供大型词典的加速:

[{'attendance': v, 'date': k} for k, v in my_dict.iteritems()]

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM