如何从 python 字典中删除 None 值?

How can I remove None value from python dictionary?

我有这样的 python 字典

data_dict = {'col_1': [{'size': 3}, {'classes': 'my-3 text-light text-center bg-primary'}, {'styles': [{'font-size': '14px'}]}]}

使用 jmespath 库,我试图像这样实现字典的预期结果

{'size':3, 'classes':'my-3 text-light text-center bg-primary', 'styles':[{'font-size': '14px'}]}

根据 jmespath 文档 MultiSelect,我最终是这样的:

jmespath.search('*[].{size:size, class:classes, styles:styles}', data_dict)

因此,我得到了不必要的 key/value 对 None 值字典

[{'size': 3, 'class': None, 'styles': None}, {'size': None, 'class': 'my-3 text-light text-center bg-primary', 'styles': None}, {'size': None, 'class': None, 'styles': [{'font-size': '14px'}]}]

我的问题是如何删除 key/value None 以获得我想要的结果?谢谢。

NewDictList = []
res = [{'size': 3, 'class': None, 'styles': None}, {'size': None, 'class': 'my-3 text-light text-center bg-primary', 'styles': None}, {'size': None, 'class': None, 'styles': [{'font-size': '14px'}]}]
for dict_values in res:
    result = {key: value for key, value in dict_values.items() if value is not None}
    NewDictList.append(result)
print(NewDictList)
#result is [{'size': 3}, {'class': 'my-3 text-light text-center bg-primary'}, {'styles': [{'font-size': '14px'}]}]