Python - Dictionary list writing to CSV as string, not list - cannot parse into pandas later on

224 Views Asked by At

for k,v in groupDict_sanitized.items():

    if discovered_hosts_groupid in v:
        csvdata = (k,v)
        print(k,v)
        print(type(v))
        
        #Example from print output
        #20099 ['5']
        #<class 'list'>
        #20100 ['5']
        #<class 'list'>
        #20105 ['5']
        #<class 'list'>
        #20114 ['5']
        #<class 'list'>
        write_discovered_hosts_raw_csv.writerows([csvdata])

    if offboarded_groupid in v:
        #v = list(v)
        csvdata = (k,v)
        print(k,v)
        print(type(v))

        
        #Example from print output:
        #19621 ['192', '359']
        #<class 'list'>
        #19636 ['19', '23', '56', '192']
        #<class 'list'>
        #19657 ['19', '21', '64', '192', '408']
        #<class 'list'>
        #19667 ['192']

        write_offboarded_hosts_raw_csv.writerows([csvdata])

The Discovered_host CSV output, shown in the photo does not have "" around the list(although only a single list entry) is a class . When writing csvdata - it shows as a list without quotes:
Discovered_host output

The CSV shows on the 'offboarded_hosts' file, quotes on the string on multiple entries - but not single list items:
Offboarded Host output

The issue here is, when re-reading this later in different code, it shows as an empty data frame due to the "[list]" entry where the CSV without quotes does read as a proper data frame.

Is there a rule I'm missing on CSV list writing to place this as a non-quoted list but keeping this desired format?

1

There are 1 best solutions below

0
On

Suggestion: Is it possible to evaluate each line and if its length is <2 you build a list out of it?