-3
name = {} 

name["one"] = "onestring"
name["two"] = "twostring"
name["three"] = [1, 2, 3, 4]
name["four"] = ["string", "hello"]

Expected output should be like

one            two           three      four

onestring    twostring        1         string
                              2         hello
                              3
                              4

how to create a csv file with above format? Dictionary values has some normal string values and some has list values. How to create a csv with above format??

2 Answers2

0

You can do this :

import csv

name = {'one': 'onestring', 'two': 'twostring', 'three': [1, 2, 3, 4], 'four': ['string', 'hello']}

# Be sure types are str or list only
assert(all(type(x) in (str, list) for x in name.values()))

csv_filename = "names.csv"

# Get length of the biggest list
max_length = 0
for key in name:
    value = name[key]
    if type(value) is list:
        list_length = len(value)
        if list_length > max_length:
            max_length = list_length


# Replace strings and lists by only lists, of equal length
equal_lengths_dict = dict()
for key in name:
    value = name[key]
    if type(value) is str:
        replacement_list = [""] * max_length
        replacement_list[0] = value
        equal_lengths_dict[key] = replacement_list
    elif type(value) is list:
        value_length = len(value)
        if value_length < max_length:
            number_empty_strings_to_add = max_length - value_length
            empty_strings_to_add = [""] * number_empty_strings_to_add
            replacement_list = value + empty_strings_to_add
            equal_lengths_dict[key] = replacement_list
        elif value_length == max_length:
            equal_lengths_dict[key] = value
        else:
            print("error")
    else:
        print("error")


# Get field names (header row of csv)
fieldnames = list(name.keys())

# Get values that will be on the same rows
csv_rows = list()
# Csv header
csv_rows.append(fieldnames)
# Other rows
list_of_values = equal_lengths_dict.values()
for index in range(max_length):
        one_row = list()
        for value in list_of_values:
            one_row.append(value[index])
        csv_rows.append(one_row)


with open(csv_filename, "w", newline="") as f:
    writer = csv.writer(f, delimiter="\t")
    writer.writerows(csv_rows)

You will have to add some checkings and tests.

Perhaps you could rename the title of your question with someting like this : "Writing a dictionary to csv file with key/value pairs representing columns and with values of unequal length (strings and lists of variable lengths)".

Rivers
  • 1,783
  • 1
  • 8
  • 27
  • Yes it does, the output of this code is what you wrote as the expected output. Could you provide more information than "No, it's not working " so I could help you ? – Rivers Oct 06 '20 at 17:17
  • The good thing about continuing on stackoverflow is that it could help others. – Rivers Oct 06 '20 at 17:23
  • the output of your code is onetwothreefour onestringtwostring1string 2hello 3 4 – Sunny Reddy Oct 06 '20 at 17:33
  • but i wanted output like i posted in my question... – Sunny Reddy Oct 06 '20 at 17:35
  • Try to read what Pranav Hosangadi said in his comment. And if you want, post an expected output as comma separated csv in order to be clearer. – Rivers Oct 06 '20 at 17:40
0

A short solution (mostly from here Creating dataframe from a dictionary where entries have different lengths (duplicate?)):

import pandas as pd

name = {}

name["one"] = "onestring"
name["two"] = "twostring"
name["three"] = [1, 2, 3, 4]
name["four"] = ["string", "hello"]

df = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in name.items() ]))

df.to_csv("tmp.csv")

print(df)

output:

         one        two  three    four
0  onestring  twostring      1  string
1        NaN        NaN      2   hello
2        NaN        NaN      3     NaN
3        NaN        NaN      4     NaN
D-E-N
  • 1,242
  • 7
  • 14
  • Yes this is working and another thing is we can do this pd.DataFrame.from_dict(name) and replace the duplicates with null values – Sunny Reddy Oct 06 '20 at 18:01