Home > front end >  Exporting a dictionary of dictionary into a CSV file converts inner values in unwanted strings
Exporting a dictionary of dictionary into a CSV file converts inner values in unwanted strings

Time:04-03

I have a dictionary that holds as values another dictionary of 10 keys with its respective values as list.

As an example following is key 655 values:

655: {
    {
        0: [],
        1: [],
        2: [],
        3: [],
        4: [],
        5: [],
        6: [],
        7: [],
        8: [
            [299, 0.4444444444444444, 0],
            [627, 0.4444444444444444, 0],
            [300, 0.2222222222222222, 0],
            [628, 0.2222222222222222, 0],
            [301, 0.1111111111111111, 0],
            [629, 0.1111111111111111, 0],
            [302, 0.2222222222222222, 0],
            [630, 0.2222222222222222, 0]
        ],
        9: []
    }
}

My problem is that when I export the dictionary intop a csv file and imported from another script I get the following result:

    '655': [
        '{0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [[299, 0.4444444444444444, 0], [627, 0.4444444444444444, 0], [300, 0.2222222222222222, 0], [628, 0.2222222222222222, 0], [301, 0.1111111111111111, 0], [629, 0.1111111111111111, 0], [302, 0.2222222222222222, 0], [630, 0.2222222222222222, 0]], 9: []}'
    ]
}

I have already sort out the key issue converting it back to int but I don't know how to recover the value as dictionary, instead of getting it as a string.

CodePudding user response:

Following @enke's suggestion the following provides a solution to my issue.

First I import the data as:

data = {}
with open('probabilities.csv', mode='r') as input:
    reader = csv.reader(input)

    data = {rows[0]:rows[1] for rows in reader}

input.close()

Then I reconvert the key from the main dictionary and its values back to a dictionary of ten keys and its values as list.

probabilities = {}

for k, v in data.items():
    probabilities[int(k)] = ast.literal_eval(v)

Obtaining a new dictionary with the desired result:

655: {
{
    0: [],
    1: [],
    2: [],
    3: [],
    4: [],
    5: [],
    6: [],
    7: [],
    8: [
        [299, 0.4444444444444444, 0],
        [627, 0.4444444444444444, 0],
        [300, 0.2222222222222222, 0],
        [628, 0.2222222222222222, 0],
        [301, 0.1111111111111111, 0],
        [629, 0.1111111111111111, 0],
        [302, 0.2222222222222222, 0],
        [630, 0.2222222222222222, 0]
    ],
    9: []
}

}

  • Related