def restore_yaml_comments(data, default_data):
 comment_map = dict()
 default_lines = iter(default_data.splitlines())
 for line in default_lines:
  if (not line):
   comment = u'\n'
  elif line.startswith(u'#'):
   comment = u'{0}\n'.format(line)
  else:
   continue
  while True:
   line = next(default_lines)
   if (line and (not line.startswith(u'#'))):
    break
   comment += u'{0}\n'.format(line)
  key = line.split(u':')[0].strip()
  comment_map[key] = comment
 out_lines = iter(data.splitlines())
 out_data = u''
 for line in out_lines:
  key = line.split(u':')[0].strip()
  if (key in comment_map):
   out_data += comment_map[key]
  out_data += u'{0}\n'.format(line)
 return out_data

def restore_yaml_comments ( data , default_data ) : comment_map = dict ( ) default_lines = iter ( default_data . splitlines ( ) ) for line in default_lines : if ( not line ) : comment = u'\n' elif line . startswith ( u'#' ) : comment = u'{0}\n' . format ( line ) else : continue while True : line = next ( default_lines ) if ( line and ( not line . startswith ( u'#' ) ) ) : break comment += u'{0}\n' . format ( line ) key = line . split ( u':' ) [ 0 ] . strip ( ) comment_map [ key ] = comment out_lines = iter ( data . splitlines ( ) ) out_data = u'' for line in out_lines : key = line . split ( u':' ) [ 0 ] . strip ( ) if ( key in comment_map ) : out_data += comment_map [ key ] out_data += u'{0}\n' . format ( line ) return out_data
scan default_data for comments and place them before the same keys in data .