Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove "None" from iteration in a dictionary

I have a list of dictionaries with various keys and values. I am trying to group it based on the keys

from itertools import chain, zip_longest 

data = [
    {'a': 2, 'b': 4, 'c': 3, 'd': 2},   
    {'b': 2, 'c': 2, 'd': 5, 'e': 4, 'f': 1},
    {'a': 2, 'd': 2, 'e': 6, 'f': 5, 'g': 12},
    {'b': 2, 'd': 2, 'e': 6, 'f': 6},
    {'c': 5, 'e': 33, 'g': 21, 'h': 56, 'i': 21}
    ]

print(type(data))

bar ={
    k: [d.get(k) for d in data]
    for k in chain.from_iterable(data)
}

print(bar)

My Output:

{'a': [2, None, 2, None, None], 'b': [4, 2, None, 2, None], 
'c': [3, 2, None, None, 5], 'd':[2, 5, 2, 2, None], 'e': [None, 4, 6, 6, 33], 
'f': [None, 1, 5, 6, None], 'g': [None, None, 12, None, 21], 
'h': [None, None, None, None, 56], 'i': [None, None, None, None, 21]}

I don't want to display "None" in the values

Desired Output:

 {'a': [2, 2], 'b': [4, 2, 2], 'c': [3, 2, 5], 'd':[2, 5, 2, 2], 'e': [4, 6, 6, 33], 
'f': [1, 5, 6], 'g': [1221], 'h': [56], 'i': [21]}

I tried to use filter function too but it dodn't worked out. Any guidance on how to remove None?

Code

like image 337
John Avatar asked Dec 22 '22 21:12

John


1 Answers

Try this:

from operator import is_not
from functools import partial

{ k: list(filter(partial(is_not, None), v)) for k, v in d.items() }

Input: {'x': [0, 23, 234, 89, None, 0, 35, 9] }

Output: {'x': [0, 23, 234, 89, 0, 35, 9]}

like image 145
Phoenix Avatar answered Jan 10 '23 03:01

Phoenix