0

I have the python dictionary like this

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

Using jmespath library, I tried to achieve the desired result of dictionary like this

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

According to jmespath documentation MultiSelect, I ended up as this:

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

As a result, I got unnecessary key/value pair of None value dictionary as so

[{'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'}]}]

My question is how can I remove key/value None in order to get my desired result? Thanks.

Houy Narun
  • 1,557
  • 5
  • 37
  • 86
  • see this post if that helps https://stackoverflow.com/questions/33797126/proper-way-to-remove-keys-in-dictionary-with-none-values-in-python – Umair Mubeen Oct 30 '20 at 19:41
  • Here you have a very good answer https://stackoverflow.com/questions/33797126/proper-way-to-remove-keys-in-dictionary-with-none-values-in-python – pepe_botika69 Nov 29 '21 at 19:35

1 Answers1

3
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'}]}]

Umair Mubeen
  • 823
  • 4
  • 22