【发布时间】:2017-06-05 13:20:17
【问题描述】:
尝试从list 中解压不是None 的dicts:
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
预期结果:
{'key': 'a', 'key_2': 'b'}
什么是正确的语法?
【问题讨论】:
标签: python dictionary list-comprehension dictionary-comprehension