Saving defaultdict(list) to a csv fileHow do I check if a list is empty?How do I sort a list of dictionaries by a value of the dictionary?How do I check whether a file exists without exceptions?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow to make a flat list out of list of lists?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?

Isometric embedding of a genus g surface

Showing mass murder in a kid's book

Quoting Keynes in a lecture

How to leave product feedback on macOS?

Can I run 125kHz RF circuit on a breadboard?

Origin of pigs as a species

Air travel with refrigerated insulin

How to get directions in deep space?

How many people need to be born every 8 years to sustain population?

Check if object is null and return null

Is there anyway, I can have two passwords for my wi-fi

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

Language involving irrational number is not a CFL

What does "tick" mean in this sentence?

Proving an identity involving cross products and coplanar vectors

Is there a reason to prefer HFS+ over APFS for disk images in High Sierra and/or Mojave?

If Captain Marvel (MCU) were to have a child with a human male, would the child be human or Kree?

Do I have to take mana from my deck or hand when tapping a dual land?

What is the meaning of "You've never met a graph you didn't like?"

Pre-Employment Background Check With Consent For Future Checks

What happens if I try to grapple an illusory duplicate from the Mirror Image spell?

Why the "ls" command is showing the permissions of files in a FAT32 partition?

How do I fix the group tension caused by my character stealing and possibly killing without provocation?

Alignment of six matrices



Saving defaultdict(list) to a csv file


How do I check if a list is empty?How do I sort a list of dictionaries by a value of the dictionary?How do I check whether a file exists without exceptions?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow to make a flat list out of list of lists?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?













2















I've been trying to save my dictionary to a csv file. So I want it to look something like this:



Subject value1 concussion
network3_UCA_0073_01_(0, 1) 0.57 no
network3_UCA_0073_02_(0, 1) 0.64 no
network3_UCA_0073_03_(0, 1) 0.59 no
network3_UCA_0075_01_(0, 1) 0.69 no


The dictionary looks like this:









'network3_UCA_0073_01_(0, 1)': [(0.57, 'no')]
'network3_UCA_0073_02_(0, 1)': [(0.64, 'no')]
'network3_UCA_0073_03_(0, 1)': [(0.59, 'no')]


'network3_UCA_0075_01_(0, 1)': [(0.69, 'no')]
'network3_UCA_0075_02_(0, 1)': [(0.62, 'no')]
'network3_UCA_0075_03_(0, 1)': [(0.57, 'no')]
'network3_UCA_0076_01_(0, 1)': [(0.38, 'no')]
'network3_UCA_0076_02_(0, 1)': [(0.60, 'no')]
'network3_UCA_0076_03_(0, 1)': [(0.68, 'no')]
'network3_UCA_0077_01_(0, 1)': [(0.64, 'no')]
'network3_UCA_0077_02_(0, 1)': [(0.58, 'no')]
'network3_UCA_0077_03_(0, 1)': [(0.48, 'no')]


The code I've been using to achieve this looks like the following (but unfortunately it hasn't been working):



with open(dirforR , 'a') as f: 
writer = csv.writer(f)
writer.writerow(['Subject', 'value1', 'concussion'])

for row in sorted_combined:
#print row[0]

l = [row[0]]
l.append(row[1][0])
l.append(row[1][1])
writer.writerow(l)


I'm not sure if its because the dictionary's key's are separated by n , but any help would be greatly appreciated. I've tried to figure it out with no hope.



Thanks for your help. I hope to hear back soon .
*********EDIT***********



I realized that this is no ordinary dictionary, I actually have it set to:



sorted_combined = defaultdict(list)


the reason for this is because I was merging two dictionaries together and this was the only way I was able to go about it..
Now I'm not quite sure how to move my dictionary list to a csv file.



Sorry this got a little messy.



***EDIT2 ***this is the code that was used to make my defaultdict list called: network_combined



network3 = defaultdict(list) 
combined_MDD = key : (MDD_network3[key], MDD_network3_yesno[key]) for key
in MDD_network3
combined_HC = key : (HC_network3[key], HC_network3_yesno[key]) for key in HC_network3
for k, v in chain(combined_MDD.items(), combined_HC.items()):
network3[k].append(v)
sorted_combined = k:v for k,v in network3.items() if k.endswith('(0, 1)')









share|improve this question




























    2















    I've been trying to save my dictionary to a csv file. So I want it to look something like this:



    Subject value1 concussion
    network3_UCA_0073_01_(0, 1) 0.57 no
    network3_UCA_0073_02_(0, 1) 0.64 no
    network3_UCA_0073_03_(0, 1) 0.59 no
    network3_UCA_0075_01_(0, 1) 0.69 no


    The dictionary looks like this:









    'network3_UCA_0073_01_(0, 1)': [(0.57, 'no')]
    'network3_UCA_0073_02_(0, 1)': [(0.64, 'no')]
    'network3_UCA_0073_03_(0, 1)': [(0.59, 'no')]


    'network3_UCA_0075_01_(0, 1)': [(0.69, 'no')]
    'network3_UCA_0075_02_(0, 1)': [(0.62, 'no')]
    'network3_UCA_0075_03_(0, 1)': [(0.57, 'no')]
    'network3_UCA_0076_01_(0, 1)': [(0.38, 'no')]
    'network3_UCA_0076_02_(0, 1)': [(0.60, 'no')]
    'network3_UCA_0076_03_(0, 1)': [(0.68, 'no')]
    'network3_UCA_0077_01_(0, 1)': [(0.64, 'no')]
    'network3_UCA_0077_02_(0, 1)': [(0.58, 'no')]
    'network3_UCA_0077_03_(0, 1)': [(0.48, 'no')]


    The code I've been using to achieve this looks like the following (but unfortunately it hasn't been working):



    with open(dirforR , 'a') as f: 
    writer = csv.writer(f)
    writer.writerow(['Subject', 'value1', 'concussion'])

    for row in sorted_combined:
    #print row[0]

    l = [row[0]]
    l.append(row[1][0])
    l.append(row[1][1])
    writer.writerow(l)


    I'm not sure if its because the dictionary's key's are separated by n , but any help would be greatly appreciated. I've tried to figure it out with no hope.



    Thanks for your help. I hope to hear back soon .
    *********EDIT***********



    I realized that this is no ordinary dictionary, I actually have it set to:



    sorted_combined = defaultdict(list)


    the reason for this is because I was merging two dictionaries together and this was the only way I was able to go about it..
    Now I'm not quite sure how to move my dictionary list to a csv file.



    Sorry this got a little messy.



    ***EDIT2 ***this is the code that was used to make my defaultdict list called: network_combined



    network3 = defaultdict(list) 
    combined_MDD = key : (MDD_network3[key], MDD_network3_yesno[key]) for key
    in MDD_network3
    combined_HC = key : (HC_network3[key], HC_network3_yesno[key]) for key in HC_network3
    for k, v in chain(combined_MDD.items(), combined_HC.items()):
    network3[k].append(v)
    sorted_combined = k:v for k,v in network3.items() if k.endswith('(0, 1)')









    share|improve this question


























      2












      2








      2


      1






      I've been trying to save my dictionary to a csv file. So I want it to look something like this:



      Subject value1 concussion
      network3_UCA_0073_01_(0, 1) 0.57 no
      network3_UCA_0073_02_(0, 1) 0.64 no
      network3_UCA_0073_03_(0, 1) 0.59 no
      network3_UCA_0075_01_(0, 1) 0.69 no


      The dictionary looks like this:









      'network3_UCA_0073_01_(0, 1)': [(0.57, 'no')]
      'network3_UCA_0073_02_(0, 1)': [(0.64, 'no')]
      'network3_UCA_0073_03_(0, 1)': [(0.59, 'no')]


      'network3_UCA_0075_01_(0, 1)': [(0.69, 'no')]
      'network3_UCA_0075_02_(0, 1)': [(0.62, 'no')]
      'network3_UCA_0075_03_(0, 1)': [(0.57, 'no')]
      'network3_UCA_0076_01_(0, 1)': [(0.38, 'no')]
      'network3_UCA_0076_02_(0, 1)': [(0.60, 'no')]
      'network3_UCA_0076_03_(0, 1)': [(0.68, 'no')]
      'network3_UCA_0077_01_(0, 1)': [(0.64, 'no')]
      'network3_UCA_0077_02_(0, 1)': [(0.58, 'no')]
      'network3_UCA_0077_03_(0, 1)': [(0.48, 'no')]


      The code I've been using to achieve this looks like the following (but unfortunately it hasn't been working):



      with open(dirforR , 'a') as f: 
      writer = csv.writer(f)
      writer.writerow(['Subject', 'value1', 'concussion'])

      for row in sorted_combined:
      #print row[0]

      l = [row[0]]
      l.append(row[1][0])
      l.append(row[1][1])
      writer.writerow(l)


      I'm not sure if its because the dictionary's key's are separated by n , but any help would be greatly appreciated. I've tried to figure it out with no hope.



      Thanks for your help. I hope to hear back soon .
      *********EDIT***********



      I realized that this is no ordinary dictionary, I actually have it set to:



      sorted_combined = defaultdict(list)


      the reason for this is because I was merging two dictionaries together and this was the only way I was able to go about it..
      Now I'm not quite sure how to move my dictionary list to a csv file.



      Sorry this got a little messy.



      ***EDIT2 ***this is the code that was used to make my defaultdict list called: network_combined



      network3 = defaultdict(list) 
      combined_MDD = key : (MDD_network3[key], MDD_network3_yesno[key]) for key
      in MDD_network3
      combined_HC = key : (HC_network3[key], HC_network3_yesno[key]) for key in HC_network3
      for k, v in chain(combined_MDD.items(), combined_HC.items()):
      network3[k].append(v)
      sorted_combined = k:v for k,v in network3.items() if k.endswith('(0, 1)')









      share|improve this question
















      I've been trying to save my dictionary to a csv file. So I want it to look something like this:



      Subject value1 concussion
      network3_UCA_0073_01_(0, 1) 0.57 no
      network3_UCA_0073_02_(0, 1) 0.64 no
      network3_UCA_0073_03_(0, 1) 0.59 no
      network3_UCA_0075_01_(0, 1) 0.69 no


      The dictionary looks like this:









      'network3_UCA_0073_01_(0, 1)': [(0.57, 'no')]
      'network3_UCA_0073_02_(0, 1)': [(0.64, 'no')]
      'network3_UCA_0073_03_(0, 1)': [(0.59, 'no')]


      'network3_UCA_0075_01_(0, 1)': [(0.69, 'no')]
      'network3_UCA_0075_02_(0, 1)': [(0.62, 'no')]
      'network3_UCA_0075_03_(0, 1)': [(0.57, 'no')]
      'network3_UCA_0076_01_(0, 1)': [(0.38, 'no')]
      'network3_UCA_0076_02_(0, 1)': [(0.60, 'no')]
      'network3_UCA_0076_03_(0, 1)': [(0.68, 'no')]
      'network3_UCA_0077_01_(0, 1)': [(0.64, 'no')]
      'network3_UCA_0077_02_(0, 1)': [(0.58, 'no')]
      'network3_UCA_0077_03_(0, 1)': [(0.48, 'no')]


      The code I've been using to achieve this looks like the following (but unfortunately it hasn't been working):



      with open(dirforR , 'a') as f: 
      writer = csv.writer(f)
      writer.writerow(['Subject', 'value1', 'concussion'])

      for row in sorted_combined:
      #print row[0]

      l = [row[0]]
      l.append(row[1][0])
      l.append(row[1][1])
      writer.writerow(l)


      I'm not sure if its because the dictionary's key's are separated by n , but any help would be greatly appreciated. I've tried to figure it out with no hope.



      Thanks for your help. I hope to hear back soon .
      *********EDIT***********



      I realized that this is no ordinary dictionary, I actually have it set to:



      sorted_combined = defaultdict(list)


      the reason for this is because I was merging two dictionaries together and this was the only way I was able to go about it..
      Now I'm not quite sure how to move my dictionary list to a csv file.



      Sorry this got a little messy.



      ***EDIT2 ***this is the code that was used to make my defaultdict list called: network_combined



      network3 = defaultdict(list) 
      combined_MDD = key : (MDD_network3[key], MDD_network3_yesno[key]) for key
      in MDD_network3
      combined_HC = key : (HC_network3[key], HC_network3_yesno[key]) for key in HC_network3
      for k, v in chain(combined_MDD.items(), combined_HC.items()):
      network3[k].append(v)
      sorted_combined = k:v for k,v in network3.items() if k.endswith('(0, 1)')






      python list csv dictionary






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 7 at 12:28







      J.Doe

















      asked Mar 7 at 3:03









      J.DoeJ.Doe

      384




      384






















          2 Answers
          2






          active

          oldest

          votes


















          2














          You can use csv's dictionary writer for this, simply do a:



          import csv
          csv.DictWriter(open("path/to/writefile.csv","wb"),fieldnames=dict_to_write[dict_to_write.keys()[0]].keys(),delimiter=","")


          alternatively you can use pandas as a more easier option:



          import pandas as pd
          pd.DataFrame(dict_to_write).to_csv("file.csv")


          for you particular use case, assuming the sample you have given is in a file:



          import pandas as pd
          with open("dictionary.txt","r") as file:
          raw_d=file.read().splitlines()
          raw_d=[eval(x) for x in raw_d if len(x)>2]
          pd.DataFrame([(k,v[0][0],v[0][1]) for x in raw_d for k,v in x.items()]).to_csv("converted_dict.csv")





          share|improve this answer

























          • Hi @Inder, thank you for your response.. But this won't work either. I just tried it. Maybe it won't work because my dictionary is printing each key line by line (not sure why) instead of being separated by commas. I'm not sure how to fix this. Any idea how I can go about it?

            – J.Doe
            Mar 7 at 3:16






          • 1





            @J.Doe kindly check the updated asnwer

            – Inder
            Mar 7 at 4:39











          • Thanks @Inder I was just wondering where in the updated answer you provided should I input the defaultdict(list)? it is represented by name dict. This information is not in a file.

            – J.Doe
            Mar 7 at 5:05












          • @so print (dict) looks like your sample??? it is a variable that outputs your sample?? it's a nested dictionary?

            – Inder
            Mar 7 at 5:46












          • I added more code to clarify how I got to this. But I replaced dict variable name with sorted_combined. I made a mistake with naming. So I'm working with a defaultdictionary(list) called sorted_combined. I showed the steps as to how I got it.

            – J.Doe
            Mar 7 at 12:30


















          1














          With some editing I think i was able to work with your example



          with open(dirforR , 'a') as f: 
          writer = csv.writer(f)
          writer.writerow(['Subject', 'value1', 'concussion'])

          for row in sorted_combined:
          if len(row)==0:
          pass
          else:
          l=[val[0] for val in row.items()]
          for value in list([val[0] for val in row.values()][0]):
          l.append(value)
          writer.writerow(l)


          hope it helps






          share|improve this answer























          • Thank you so much! it actually works :) But just a small followup question, in my csv file I'm getting something that looks like this: network3_QNS_0044_01_(0, 1) 0.498 no network3_QNS_0044_02_(0, 1) 0.452 network3_QNS_0044_02_(0, 1) 0.452 no network3_QNS_0044_03_(0, 1) 0.613 so it seems like its repeating the same subject twice each time... once with the second column one without it. Do you know why this might be happening and how to fix it? @TavoGLC

            – J.Doe
            Mar 7 at 12:47







          • 1





            Perhaps in the second column instead of 'no' or 'yes' you have an empty string '' causing that behavior. Try to check all the data before the dictionary generation.

            – TavoGLC
            Mar 7 at 19:14











          • you're right. I realized I do have empty strings but I don't know how to not include them. I thought maybe this part of the code:` if len(row)==0` would solve that problem. Do you know what I could add to this code to fix this issue?

            – J.Doe
            Mar 7 at 21:02











          • Try adding an if statement over the dictionary generation, somehing like key : (MDD_network3[key], MDD_network3_yesno[key]) for key in MDD_network3 if len(MDD_network3_yesno[key])!=0 for both dictionaries

            – TavoGLC
            Mar 7 at 22:41










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55035396%2fsaving-defaultdictlist-to-a-csv-file%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          You can use csv's dictionary writer for this, simply do a:



          import csv
          csv.DictWriter(open("path/to/writefile.csv","wb"),fieldnames=dict_to_write[dict_to_write.keys()[0]].keys(),delimiter=","")


          alternatively you can use pandas as a more easier option:



          import pandas as pd
          pd.DataFrame(dict_to_write).to_csv("file.csv")


          for you particular use case, assuming the sample you have given is in a file:



          import pandas as pd
          with open("dictionary.txt","r") as file:
          raw_d=file.read().splitlines()
          raw_d=[eval(x) for x in raw_d if len(x)>2]
          pd.DataFrame([(k,v[0][0],v[0][1]) for x in raw_d for k,v in x.items()]).to_csv("converted_dict.csv")





          share|improve this answer

























          • Hi @Inder, thank you for your response.. But this won't work either. I just tried it. Maybe it won't work because my dictionary is printing each key line by line (not sure why) instead of being separated by commas. I'm not sure how to fix this. Any idea how I can go about it?

            – J.Doe
            Mar 7 at 3:16






          • 1





            @J.Doe kindly check the updated asnwer

            – Inder
            Mar 7 at 4:39











          • Thanks @Inder I was just wondering where in the updated answer you provided should I input the defaultdict(list)? it is represented by name dict. This information is not in a file.

            – J.Doe
            Mar 7 at 5:05












          • @so print (dict) looks like your sample??? it is a variable that outputs your sample?? it's a nested dictionary?

            – Inder
            Mar 7 at 5:46












          • I added more code to clarify how I got to this. But I replaced dict variable name with sorted_combined. I made a mistake with naming. So I'm working with a defaultdictionary(list) called sorted_combined. I showed the steps as to how I got it.

            – J.Doe
            Mar 7 at 12:30















          2














          You can use csv's dictionary writer for this, simply do a:



          import csv
          csv.DictWriter(open("path/to/writefile.csv","wb"),fieldnames=dict_to_write[dict_to_write.keys()[0]].keys(),delimiter=","")


          alternatively you can use pandas as a more easier option:



          import pandas as pd
          pd.DataFrame(dict_to_write).to_csv("file.csv")


          for you particular use case, assuming the sample you have given is in a file:



          import pandas as pd
          with open("dictionary.txt","r") as file:
          raw_d=file.read().splitlines()
          raw_d=[eval(x) for x in raw_d if len(x)>2]
          pd.DataFrame([(k,v[0][0],v[0][1]) for x in raw_d for k,v in x.items()]).to_csv("converted_dict.csv")





          share|improve this answer

























          • Hi @Inder, thank you for your response.. But this won't work either. I just tried it. Maybe it won't work because my dictionary is printing each key line by line (not sure why) instead of being separated by commas. I'm not sure how to fix this. Any idea how I can go about it?

            – J.Doe
            Mar 7 at 3:16






          • 1





            @J.Doe kindly check the updated asnwer

            – Inder
            Mar 7 at 4:39











          • Thanks @Inder I was just wondering where in the updated answer you provided should I input the defaultdict(list)? it is represented by name dict. This information is not in a file.

            – J.Doe
            Mar 7 at 5:05












          • @so print (dict) looks like your sample??? it is a variable that outputs your sample?? it's a nested dictionary?

            – Inder
            Mar 7 at 5:46












          • I added more code to clarify how I got to this. But I replaced dict variable name with sorted_combined. I made a mistake with naming. So I'm working with a defaultdictionary(list) called sorted_combined. I showed the steps as to how I got it.

            – J.Doe
            Mar 7 at 12:30













          2












          2








          2







          You can use csv's dictionary writer for this, simply do a:



          import csv
          csv.DictWriter(open("path/to/writefile.csv","wb"),fieldnames=dict_to_write[dict_to_write.keys()[0]].keys(),delimiter=","")


          alternatively you can use pandas as a more easier option:



          import pandas as pd
          pd.DataFrame(dict_to_write).to_csv("file.csv")


          for you particular use case, assuming the sample you have given is in a file:



          import pandas as pd
          with open("dictionary.txt","r") as file:
          raw_d=file.read().splitlines()
          raw_d=[eval(x) for x in raw_d if len(x)>2]
          pd.DataFrame([(k,v[0][0],v[0][1]) for x in raw_d for k,v in x.items()]).to_csv("converted_dict.csv")





          share|improve this answer















          You can use csv's dictionary writer for this, simply do a:



          import csv
          csv.DictWriter(open("path/to/writefile.csv","wb"),fieldnames=dict_to_write[dict_to_write.keys()[0]].keys(),delimiter=","")


          alternatively you can use pandas as a more easier option:



          import pandas as pd
          pd.DataFrame(dict_to_write).to_csv("file.csv")


          for you particular use case, assuming the sample you have given is in a file:



          import pandas as pd
          with open("dictionary.txt","r") as file:
          raw_d=file.read().splitlines()
          raw_d=[eval(x) for x in raw_d if len(x)>2]
          pd.DataFrame([(k,v[0][0],v[0][1]) for x in raw_d for k,v in x.items()]).to_csv("converted_dict.csv")






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 7 at 4:38

























          answered Mar 7 at 3:10









          InderInder

          2,07951226




          2,07951226












          • Hi @Inder, thank you for your response.. But this won't work either. I just tried it. Maybe it won't work because my dictionary is printing each key line by line (not sure why) instead of being separated by commas. I'm not sure how to fix this. Any idea how I can go about it?

            – J.Doe
            Mar 7 at 3:16






          • 1





            @J.Doe kindly check the updated asnwer

            – Inder
            Mar 7 at 4:39











          • Thanks @Inder I was just wondering where in the updated answer you provided should I input the defaultdict(list)? it is represented by name dict. This information is not in a file.

            – J.Doe
            Mar 7 at 5:05












          • @so print (dict) looks like your sample??? it is a variable that outputs your sample?? it's a nested dictionary?

            – Inder
            Mar 7 at 5:46












          • I added more code to clarify how I got to this. But I replaced dict variable name with sorted_combined. I made a mistake with naming. So I'm working with a defaultdictionary(list) called sorted_combined. I showed the steps as to how I got it.

            – J.Doe
            Mar 7 at 12:30

















          • Hi @Inder, thank you for your response.. But this won't work either. I just tried it. Maybe it won't work because my dictionary is printing each key line by line (not sure why) instead of being separated by commas. I'm not sure how to fix this. Any idea how I can go about it?

            – J.Doe
            Mar 7 at 3:16






          • 1





            @J.Doe kindly check the updated asnwer

            – Inder
            Mar 7 at 4:39











          • Thanks @Inder I was just wondering where in the updated answer you provided should I input the defaultdict(list)? it is represented by name dict. This information is not in a file.

            – J.Doe
            Mar 7 at 5:05












          • @so print (dict) looks like your sample??? it is a variable that outputs your sample?? it's a nested dictionary?

            – Inder
            Mar 7 at 5:46












          • I added more code to clarify how I got to this. But I replaced dict variable name with sorted_combined. I made a mistake with naming. So I'm working with a defaultdictionary(list) called sorted_combined. I showed the steps as to how I got it.

            – J.Doe
            Mar 7 at 12:30
















          Hi @Inder, thank you for your response.. But this won't work either. I just tried it. Maybe it won't work because my dictionary is printing each key line by line (not sure why) instead of being separated by commas. I'm not sure how to fix this. Any idea how I can go about it?

          – J.Doe
          Mar 7 at 3:16





          Hi @Inder, thank you for your response.. But this won't work either. I just tried it. Maybe it won't work because my dictionary is printing each key line by line (not sure why) instead of being separated by commas. I'm not sure how to fix this. Any idea how I can go about it?

          – J.Doe
          Mar 7 at 3:16




          1




          1





          @J.Doe kindly check the updated asnwer

          – Inder
          Mar 7 at 4:39





          @J.Doe kindly check the updated asnwer

          – Inder
          Mar 7 at 4:39













          Thanks @Inder I was just wondering where in the updated answer you provided should I input the defaultdict(list)? it is represented by name dict. This information is not in a file.

          – J.Doe
          Mar 7 at 5:05






          Thanks @Inder I was just wondering where in the updated answer you provided should I input the defaultdict(list)? it is represented by name dict. This information is not in a file.

          – J.Doe
          Mar 7 at 5:05














          @so print (dict) looks like your sample??? it is a variable that outputs your sample?? it's a nested dictionary?

          – Inder
          Mar 7 at 5:46






          @so print (dict) looks like your sample??? it is a variable that outputs your sample?? it's a nested dictionary?

          – Inder
          Mar 7 at 5:46














          I added more code to clarify how I got to this. But I replaced dict variable name with sorted_combined. I made a mistake with naming. So I'm working with a defaultdictionary(list) called sorted_combined. I showed the steps as to how I got it.

          – J.Doe
          Mar 7 at 12:30





          I added more code to clarify how I got to this. But I replaced dict variable name with sorted_combined. I made a mistake with naming. So I'm working with a defaultdictionary(list) called sorted_combined. I showed the steps as to how I got it.

          – J.Doe
          Mar 7 at 12:30













          1














          With some editing I think i was able to work with your example



          with open(dirforR , 'a') as f: 
          writer = csv.writer(f)
          writer.writerow(['Subject', 'value1', 'concussion'])

          for row in sorted_combined:
          if len(row)==0:
          pass
          else:
          l=[val[0] for val in row.items()]
          for value in list([val[0] for val in row.values()][0]):
          l.append(value)
          writer.writerow(l)


          hope it helps






          share|improve this answer























          • Thank you so much! it actually works :) But just a small followup question, in my csv file I'm getting something that looks like this: network3_QNS_0044_01_(0, 1) 0.498 no network3_QNS_0044_02_(0, 1) 0.452 network3_QNS_0044_02_(0, 1) 0.452 no network3_QNS_0044_03_(0, 1) 0.613 so it seems like its repeating the same subject twice each time... once with the second column one without it. Do you know why this might be happening and how to fix it? @TavoGLC

            – J.Doe
            Mar 7 at 12:47







          • 1





            Perhaps in the second column instead of 'no' or 'yes' you have an empty string '' causing that behavior. Try to check all the data before the dictionary generation.

            – TavoGLC
            Mar 7 at 19:14











          • you're right. I realized I do have empty strings but I don't know how to not include them. I thought maybe this part of the code:` if len(row)==0` would solve that problem. Do you know what I could add to this code to fix this issue?

            – J.Doe
            Mar 7 at 21:02











          • Try adding an if statement over the dictionary generation, somehing like key : (MDD_network3[key], MDD_network3_yesno[key]) for key in MDD_network3 if len(MDD_network3_yesno[key])!=0 for both dictionaries

            – TavoGLC
            Mar 7 at 22:41















          1














          With some editing I think i was able to work with your example



          with open(dirforR , 'a') as f: 
          writer = csv.writer(f)
          writer.writerow(['Subject', 'value1', 'concussion'])

          for row in sorted_combined:
          if len(row)==0:
          pass
          else:
          l=[val[0] for val in row.items()]
          for value in list([val[0] for val in row.values()][0]):
          l.append(value)
          writer.writerow(l)


          hope it helps






          share|improve this answer























          • Thank you so much! it actually works :) But just a small followup question, in my csv file I'm getting something that looks like this: network3_QNS_0044_01_(0, 1) 0.498 no network3_QNS_0044_02_(0, 1) 0.452 network3_QNS_0044_02_(0, 1) 0.452 no network3_QNS_0044_03_(0, 1) 0.613 so it seems like its repeating the same subject twice each time... once with the second column one without it. Do you know why this might be happening and how to fix it? @TavoGLC

            – J.Doe
            Mar 7 at 12:47







          • 1





            Perhaps in the second column instead of 'no' or 'yes' you have an empty string '' causing that behavior. Try to check all the data before the dictionary generation.

            – TavoGLC
            Mar 7 at 19:14











          • you're right. I realized I do have empty strings but I don't know how to not include them. I thought maybe this part of the code:` if len(row)==0` would solve that problem. Do you know what I could add to this code to fix this issue?

            – J.Doe
            Mar 7 at 21:02











          • Try adding an if statement over the dictionary generation, somehing like key : (MDD_network3[key], MDD_network3_yesno[key]) for key in MDD_network3 if len(MDD_network3_yesno[key])!=0 for both dictionaries

            – TavoGLC
            Mar 7 at 22:41













          1












          1








          1







          With some editing I think i was able to work with your example



          with open(dirforR , 'a') as f: 
          writer = csv.writer(f)
          writer.writerow(['Subject', 'value1', 'concussion'])

          for row in sorted_combined:
          if len(row)==0:
          pass
          else:
          l=[val[0] for val in row.items()]
          for value in list([val[0] for val in row.values()][0]):
          l.append(value)
          writer.writerow(l)


          hope it helps






          share|improve this answer













          With some editing I think i was able to work with your example



          with open(dirforR , 'a') as f: 
          writer = csv.writer(f)
          writer.writerow(['Subject', 'value1', 'concussion'])

          for row in sorted_combined:
          if len(row)==0:
          pass
          else:
          l=[val[0] for val in row.items()]
          for value in list([val[0] for val in row.values()][0]):
          l.append(value)
          writer.writerow(l)


          hope it helps







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 7 at 6:01









          TavoGLCTavoGLC

          43128




          43128












          • Thank you so much! it actually works :) But just a small followup question, in my csv file I'm getting something that looks like this: network3_QNS_0044_01_(0, 1) 0.498 no network3_QNS_0044_02_(0, 1) 0.452 network3_QNS_0044_02_(0, 1) 0.452 no network3_QNS_0044_03_(0, 1) 0.613 so it seems like its repeating the same subject twice each time... once with the second column one without it. Do you know why this might be happening and how to fix it? @TavoGLC

            – J.Doe
            Mar 7 at 12:47







          • 1





            Perhaps in the second column instead of 'no' or 'yes' you have an empty string '' causing that behavior. Try to check all the data before the dictionary generation.

            – TavoGLC
            Mar 7 at 19:14











          • you're right. I realized I do have empty strings but I don't know how to not include them. I thought maybe this part of the code:` if len(row)==0` would solve that problem. Do you know what I could add to this code to fix this issue?

            – J.Doe
            Mar 7 at 21:02











          • Try adding an if statement over the dictionary generation, somehing like key : (MDD_network3[key], MDD_network3_yesno[key]) for key in MDD_network3 if len(MDD_network3_yesno[key])!=0 for both dictionaries

            – TavoGLC
            Mar 7 at 22:41

















          • Thank you so much! it actually works :) But just a small followup question, in my csv file I'm getting something that looks like this: network3_QNS_0044_01_(0, 1) 0.498 no network3_QNS_0044_02_(0, 1) 0.452 network3_QNS_0044_02_(0, 1) 0.452 no network3_QNS_0044_03_(0, 1) 0.613 so it seems like its repeating the same subject twice each time... once with the second column one without it. Do you know why this might be happening and how to fix it? @TavoGLC

            – J.Doe
            Mar 7 at 12:47







          • 1





            Perhaps in the second column instead of 'no' or 'yes' you have an empty string '' causing that behavior. Try to check all the data before the dictionary generation.

            – TavoGLC
            Mar 7 at 19:14











          • you're right. I realized I do have empty strings but I don't know how to not include them. I thought maybe this part of the code:` if len(row)==0` would solve that problem. Do you know what I could add to this code to fix this issue?

            – J.Doe
            Mar 7 at 21:02











          • Try adding an if statement over the dictionary generation, somehing like key : (MDD_network3[key], MDD_network3_yesno[key]) for key in MDD_network3 if len(MDD_network3_yesno[key])!=0 for both dictionaries

            – TavoGLC
            Mar 7 at 22:41
















          Thank you so much! it actually works :) But just a small followup question, in my csv file I'm getting something that looks like this: network3_QNS_0044_01_(0, 1) 0.498 no network3_QNS_0044_02_(0, 1) 0.452 network3_QNS_0044_02_(0, 1) 0.452 no network3_QNS_0044_03_(0, 1) 0.613 so it seems like its repeating the same subject twice each time... once with the second column one without it. Do you know why this might be happening and how to fix it? @TavoGLC

          – J.Doe
          Mar 7 at 12:47






          Thank you so much! it actually works :) But just a small followup question, in my csv file I'm getting something that looks like this: network3_QNS_0044_01_(0, 1) 0.498 no network3_QNS_0044_02_(0, 1) 0.452 network3_QNS_0044_02_(0, 1) 0.452 no network3_QNS_0044_03_(0, 1) 0.613 so it seems like its repeating the same subject twice each time... once with the second column one without it. Do you know why this might be happening and how to fix it? @TavoGLC

          – J.Doe
          Mar 7 at 12:47





          1




          1





          Perhaps in the second column instead of 'no' or 'yes' you have an empty string '' causing that behavior. Try to check all the data before the dictionary generation.

          – TavoGLC
          Mar 7 at 19:14





          Perhaps in the second column instead of 'no' or 'yes' you have an empty string '' causing that behavior. Try to check all the data before the dictionary generation.

          – TavoGLC
          Mar 7 at 19:14













          you're right. I realized I do have empty strings but I don't know how to not include them. I thought maybe this part of the code:` if len(row)==0` would solve that problem. Do you know what I could add to this code to fix this issue?

          – J.Doe
          Mar 7 at 21:02





          you're right. I realized I do have empty strings but I don't know how to not include them. I thought maybe this part of the code:` if len(row)==0` would solve that problem. Do you know what I could add to this code to fix this issue?

          – J.Doe
          Mar 7 at 21:02













          Try adding an if statement over the dictionary generation, somehing like key : (MDD_network3[key], MDD_network3_yesno[key]) for key in MDD_network3 if len(MDD_network3_yesno[key])!=0 for both dictionaries

          – TavoGLC
          Mar 7 at 22:41





          Try adding an if statement over the dictionary generation, somehing like key : (MDD_network3[key], MDD_network3_yesno[key]) for key in MDD_network3 if len(MDD_network3_yesno[key])!=0 for both dictionaries

          – TavoGLC
          Mar 7 at 22:41

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55035396%2fsaving-defaultdictlist-to-a-csv-file%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved