Search code examples
pythondefaultdict

Store defaultdict into a text file


I have a defaultdict test which looks like that :

defaultdict(<type 'list'>, {'A': [['Age','19'], ['Name','Peter'], ['Country','Australia]], 'B': [['Age','22'], ['Name','Paul'], ['Country','England']], 'C': ... ]]})

I want to output that defauldict into new files with keys as filenames. I can do it with :

for k,v in test.items():
        with open("{}_test.txt".format(k), "w") as f:
                csv='\n'.join(['\n'.join(t) for t in v])
                f.write("%s,%s\n" % (k, csv))

That works, but the problem I have is : when I check the content of the file, it looks like that :

cat A_test.txt

    A,Age
    19
    Name
    Peter
    Country
    Australia
    
cat B_test.txt

    B,Age
    22
    Name
    Paul
    Country
    England

I don't want the "A," and "B," at the beginning of the first line of the files. It should be like that :

cat A_test.txt
    
        Age
        19
        Name
        Peter
        Country
        Australia
        
    cat B_test.txt
    
        Age
        22
        Name
        Paul
        Country
        England

Any solution to solve that?


Solution

  • In the last line, remove the k, which prints the key ?

    f.write("%s\n" % ( csv))