Home > Software engineering >  Creating a dict using two lists but formatting them differently
Creating a dict using two lists but formatting them differently

Time:11-08

I am forced to ask on here after embarrassingly failing to think of a quick solution myself. So I have the following:

keys= ["car", "cat", "sky"]
value_a = ['red', 'furry','cloudy']
value_b = ['blue', 'puffy','rainy']
value_c = ['yellow', 'pet','clear']
all_data = [value_a ,value_b,value_c]

def csv_exporter(keys, all_data):
    dictionary = dict(zip(keys, all_data))
    df = pd.DataFrame(dictionary)
    print(df)

csv_exporter(keys, all_data)

and so then my output is:

      car    cat     sky
0     red   blue  yellow
1   furry  puffy     pet
2  cloudy  rainy   clear

but what I want is this

      car    cat     sky
0     red   furry  cloudy
1     blue  puffy  rainy
2    yellow  pet   clear

Also, I am creating a dictionary first then exporting as a dataframe because that works more smoothly for my application.

CodePudding user response:

You need to zip all_data too:

def csv_exporter(keys, all_data):
    dictionary = dict(zip(keys, zip(*all_data)))
    df = pd.DataFrame(dictionary)
    print(df)

Results:

>>> csv_exporter(keys, all_data)
      car    cat     sky
0     red  furry  cloudy
1    blue  puffy   rainy
2  yellow    pet   clear

CodePudding user response:

Have you tried a simple transform?

all_data_new=[]

for element in range(len(all_data[0])):
    value_new=[]
    for dataSet in range(len(all_data)):
        value_new.append(all_data[dataSet][element])
    all_data_new.append(value_new)

all_data_new >> [['red', 'blue', 'yellow'], ['furry', 'puffy', 'pet'], ['cloudy', 'rainy', 'clear']]

  • Related