Search code examples
pythonpython-3.xcsvdictionaryexport-to-csv

Python - Write Values from Dictionary into .csv according to keys representing the position of column and row (coordinates)


I am having a dictionary where the keys represents a coordinate (column,row) of a specific value:

d={(1,1) : value_1 , (1,2) : value_2 , (2,1) : value_3 , (2,2) : value_4}

The csv-file should only contain the values, but at the right position defined by the keys (column,row):

value_1 , value_3
value_2 , value_4

I hope anybody can give me a hint, how i could handle this one?


Solution

  • If you are okay using Pandas, you could use the key coordinates to directly add the dictionary values to their appropriate location, like so:

    import pandas as pd
    
    d = {
        (1,1): 1,
        (1,2): 2,
        (2,1): 3,
        (2,2): 4
        }
    
    df = pd.DataFrame()
    for k, v in d.items():
        df.at[k[1], k[0]] = v
    
    df.to_csv('out.csv', index=False, header=False)
    

    Which would output the following data table as out.csv:

    1.0,3.0
    2.0,4.0