Intellipaat Back

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

This is my data

import numpy as np

class_data=[np.array(['class3','class5']),np.array(['claas1','class9'])]

data=[['dog.txt','cat.txt'],['mouse.txt','horse.txt']]

 

needed result is to create the dictionary that looks like that:

[[{'text': 'dog.txt', 'class': 'class3'},

  {'text': 'cat.txt', 'class': 'class5'}],

 [{'text': 'mouse.txt', 'class': 'class1'},

  {'text': 'horse.txt', 'class': 'class9'}]]

I attempt to:

out_data=[]

for kk,kb in zip(class_data,data):

    for ii,kb2 in enumerate(kb):

        for i,v in enumerate(kk):

            out_data.append({'text': kb2, 'class': v})

            

out_data

which makes every possible combination from each identical array which is wrong.

[{'text': 'dog.txt', 'class': 'class3'},

 {'text': 'dog.txt', 'class': 'class5'},

 {'text': 'cat.txt', 'class': 'class3'},

 {'text': 'cat.txt', 'class': 'class5'},

 {'text': 'mouse.txt', 'class': 'claas1'},

 {'text': 'mouse.txt', 'class': 'class9'},

 {'text': 'horse.txt', 'class': 'claas1'},

 {'text': 'horse.txt', 'class': 'class9'}]

this solution should work iteratively and also can work with the larger datasets

1 Answer

0 votes
by (36.8k points)

The below code will work:

out_data=[]

for pairs in zip(data, class_data):

    temp_list = []

    for x in zip(pairs[0], pairs[1]):       

        temp_list.append({'text': x[0], 'class': x[1]})       

    out_data.append(temp_list)

out_data

Output:

[[{'text': 'dog.txt', 'class': 'class3'},

  {'text': 'cat.txt', 'class': 'class5'}],

 [{'text': 'mouse.txt', 'class': 'claas1'},

  {'text': 'horse.txt', 'class': 'class9'}]]

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...