从列表中解压缩dict,其中key不是None

时间:2017-06-05 13:20:18

标签: python dictionary list-comprehension dictionary-comprehension

尝试从dict解压缩None的{​​{1}}:

list

尝试了一个词典理解

In [4]: unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]

列表理解:

In [5]: {key: value for (key, value) in unpack_dict if (key, value) is not None}
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-ec0e44b95586> in <module>()
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

<ipython-input-5-ec0e44b95586> in <dictcomp>(.0)
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

ValueError: not enough values to unpack (expected 2, got 1)

预期结果:

In [6]: {**[x for x in [unpack_dict] if x is not None]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ac36898d39a1> in <module>()
----> 1 {**[x for x in [unpack_dict] if x is not None]}

TypeError: 'list' object is not a mapping

什么是正确的语法?

3 个答案:

答案 0 :(得分:4)

您正尝试将字典或None解包为两个变量(keyvalue)。您无法以这种方式解压缩 None不可迭代,并且对dict的迭代将只产生,而不是值。

如果有字典,则遍历字典项,否则循环遍历空序列,并解压缩迭代结果

{key: value for d in unpack_dict for key, value in (d.items() if d else ())}

d.items() if d else ()表达式从(非空)字典生成(key, value)个可迭代对,或者生成空元组(导致嵌套迭代立即停止)。

演示:

>>> unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]
>>> {key: value for d in unpack_dict for key, value in (d.items() if d else ())}
{'key': 'a', 'key_2': 'b'}

答案 1 :(得分:2)

FWIW,您可以使用for循环以及对dict.update的连续调用来执行此操作,我认为这些调用非常易读:

>>> dct = {}
>>> for d in unpack_dict:
...    if d:
...       dct.update(d)
... 
>>> dct
{'key': 'a', 'key_2': 'b'}

答案 2 :(得分:1)

使用内置函数filter

假设你确实有一个dicts列表或None,根据你的例子:

merged_dict = {}
for dict in filter(None, unpack_dict):
    merged_dict.update(dict)

或者在一行中:

dict(pair for dict in filter(None, unpack_dict) for pair in dict.items())

或者如果您的输入应该是元组的列表,那么它非常简单,与您尝试的类似:

unpack_dict = [('key': 'a'), ('key_2': 'b'), None]
{key: value for (key, value) in filter(None, unpack_dict)}