Search code examples
pythoncsvyaml

csv file from yaml in python


4:
- a: [0.6511928334730416, -0.6444996859128429, 0.40070930065859994]
  b: [-70.26386506067132, 19.563101216582368, 315.91419304402643]
  c: [462, 429, 401, 389]
  d: 1
5:
- e: [0.6511928334730416, -0.6444996859128429, 0.40070930065859994]
  f: [-70.26386506067132, 19.563101216582368, 315.91419304402643]
  g: [462, 429, 401, 389]
  h: 1

This is my yml format and I have to extract only the values of key c and g from it and create a csv file. I am new to python.
Can anyone guide me here thanks in advance


Solution

  • If your yaml converted to dict is similar to this :

    d = {4:
           {
          'a': [0.6511928334730416, -0.6444996859128429, 0.40070930065859994],
          'b': [-70.26386506067132, 19.563101216582368, 315.91419304402643],
          'c': [462, 429, 401, 389],
          'd': 1
           },
        5:
         {'e': [0.6511928334730416, -0.6444996859128429, 0.40070930065859994],
          'f': [-70.26386506067132, 19.563101216582368, 315.91419304402643],
          'g': [462, 429, 401, 380],
          'h': 1
         }
        }
    

    The following code you can try to convert the values to CSV :

    import csv  
    import itertools  
    
    # taking only the values of keys 'c' and 'g'
    li = [i[j] for i in d.values()  for j in i.keys()  if j == "c" or j == "g"]
    
    # the above list of list making a flat list for better result
    merged = list(itertools.chain.from_iterable(li))
    
    with open("filename.csv",'w') as myfile:
        wr = csv.writer(myfile, lineterminator='\n')
        # If you want first list to csv you can use li instead of merged 
        wr.writerow(merged)