简体   繁体   English

从字典列表中提取新字典

[英]Extract new dictionary from a list of dictionaries

I have a list of dictionaries, I would like to create a new dictionary where the first key 'value' corresponds to the second value of the 'b' key of each dictionary in the list.我有一个字典列表,我想创建一个新字典,其中第一个键'value'对应于列表中每个字典的'b'键的第二个值。 The second key 'number' of the new dictionary corresponds to the third (therefore last) value of the 'b' key of each dictionary in the list.新字典的第二个键'number'对应于列表中每个字典的'b'键的第三个(因此也是最后一个)值。

my_list = [
    {
        'a': (2.6, 0.08, 47.0, 1),
        'b': (5.7, 0.05, 1)
    },
    {
        'a': (2.6, 0.08, 47.0, 2),
        'b': (5.7, 0.06, 2)
    }
]

expected output:预期输出:

new_dic = {'value': (0.05, 0.06), number = (1, 2)}

you can use comprehension as follows:您可以按如下方式使用理解:

new_dict = {}
new_dict['value'] = tuple(val['b'][1] for val in my_list)
new_dict['number'] = tuple(val['b'][2] for val in my_list)

Note that you need to call the tuple constructor, because (val['b'][2] for val in my_list) alone returns a generator object.请注意,您需要调用元组构造函数,因为(val['b'][2] for val in my_list)单独返回一个生成器对象。

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

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