在python中具有理解能力的词典列表 [英] List of dictionaries with comprehension in python

查看:59
本文介绍了在python中具有理解能力的词典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的词典列表:

    ld=[{'a':10,'b':20},{'p':10,'u':100}]

我想写一个这样的理解:

I want to write a comprehension like this:

    [ (k,v) for k,v in [ d.items() for d in ld ] ]

基本上,我想遍历列表中的字典,并获取每个字典的键和值并做某事.

basically I want to iterate over dictionaries in the list and get the keys and values of each dict and do sth.

示例:例如,该示例的输出将是另一本没有某些键的字典列表:

Example: One example output of this would be for example another list of dictionaries without some keys:

        ld=[{'a':10,'b':20},{'p':10,'u':100}]
        new_ld=[{'a':10},{'p':10}]

但是,上述理解是不正确的.任何帮助,将不胜感激.

However, the above comprehension is not correct. Any help would be appreciated.

推荐答案

正确的列表理解是 [对于d中d的k,v是[[(k,v)for d.items()]]

演示:

>>> ld = [{'a': 10, 'b': 20}, {'p': 10, 'u': 100}]
>>> [[(k,v) for k,v in d.items()] for d in ld]
[[('a', 10), ('b', 20)], [('p', 10), ('u', 100)]]
>>> [[(k,v) for k,v in d.items() if k not in ['b','u']] for d in ld]
[[('a', 10)], [('p', 10)]]

这篇关于在python中具有理解能力的词典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆