简体   繁体   English

在python中理解的词典列表

[英]List of dictionaries with comprehension in python

I have the following list of dictionaries: 我有以下词典列表:

    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. 任何帮助,将不胜感激。

It looks like you want a list of tuples with the keys and values paired. 看起来你想要一个元组列表,其中键和值配对。

To do this you can do two for loops in a list comprehension, and use .items() to output the keys and values as tuples: 为此,您可以在列表推导中执行两个for循环,并使用.items()将键和值输出为元组:

[kv for d in ld for kv in d.items()]

outputs: 输出:

[('a', 10), ('b', 20), ('p', 10), ('u', 100)]

Correct list comprehension is [[(k,v) for k,v in d.items()] for d in ld] 正确的列表理解是[[(k,v) for k,v in d.items()] for d in ld]

Demo: 演示:

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

Use itertools.chain.from_iterable to flatten the sequence: 使用itertools.chain.from_iterable来展平序列:

>>> from itertools import chain
>>> ld = [{'a':10,'b':20},{'p':10,'u':100}]
>>> list(chain.from_iterable(d.items() for d in ld))
[('a', 10), ('b', 20), ('p', 10), ('u', 100)]

The other solution is to use double- for comprehension/generator but I find them very hard to read. 另一种解决方案是使用双for理解/发电机,但我觉得他们非常难以阅读。

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

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