Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have a dictionary like this

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

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

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

According to the jmespath documentation MultiSelect, I ended with this:

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

As the result, I got an 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 the key/value None to get my desired result? Thanks.

1 Answer

0 votes
by (36.8k points)

We can use the itertools.cycle to repeat these keys. Then we need the list comprehension that takes the length of this key list into account and we're done.

from itertools import cycle

list_values = ['event1', 'location1', 'time1', 'event2', 'location2', 'time2', 

               'event3', 'location3', 'time3', 'event4', 'location4', 'time4']

list_keys = ['event', 'location', 'time']

data = list(zip(cycle(list_keys), list_values))

result = [dict(data[i:i+len(list_keys)]) for i in range(len(data))[::len(list_keys)] ]

print(result)

from itertools import cycle

list_values = ['event1', 'location1', 'time1', 'event2', 'location2', 'time2', 'event3', 'location3', 'time3',

               'event4', 'location4', 'time4']

list_keys = ['event', 'location', 'time']

def chunks(lst, n):

    """Yield successive n-sized chunks from lst."""

    for i in range(0, len(lst), n):

        yield lst[i:i + n]

data = list(zip(cycle(list_keys), list_values))

result = [dict(chunk) for chunk in chunks(data, len(list_keys))]

print(result)

One the final fix. If we don't want to use the up memory by creating the list with data = list(zip(cycle(list_keys), list_values)) there's a way to create the chunks from an iterable we get with zipping. We have to import islice for that. I just list the changes to the last version.

from itertools import cycle, islice  # added islice

def chunks(iterable, n):  # new chunk function

    iterable = iter(iterable)

    return iter(lambda: list(islice(iterable, n)), [])

data = zip(cycle(list_keys), list_values)  # no more list

Want to gain skills in Data Science with Python? Sign up today for this Python for Data Science Course and be a master in it

 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...