title: Properly format SQL query when insert into variable number of columns
body: <p>I'm using <code>psycopg2</code> to interact with a <code>PostgreSQL</code> database. I have a function whereby any number of columns (from a single column to all columns) in a table could be inserted into. My question is: <em>how would one properly, dynamically, construct this query?</em></p>
  
  <p>At the moment I am using string formatting and concatenation and I know this is the absolute <strong><em>worst</em></strong> way to do this. Consider the below code where, in this case, my unknown number of columns (i.e. keys from a <code>dict</code> is in fact 2): </p>
  
  <pre><code>dictOfUnknownLength = {'key1': 3, 'key2': 'myString'}
  
  def createMyQuery(user_ids, dictOfUnknownLength):
      fields, values = list(), list()
  
      for key, val in dictOfUnknownLength.items():
          fields.append(key)
          values.append(val)
  
      fields = str(fields).replace('[', '(').replace(']', ')').replace("'", "")
      values = str(values).replace('[', '(').replace(']', ')')
  
      query = f"INSERT INTO myTable {fields} VALUES {values} RETURNING someValue;"
  </code></pre>
  
  <blockquote>
    <p><code>query = INSERT INTO myTable (key1, key2) VALUES (3, 'myString') RETURNING someValue;</code></p>
  </blockquote>
  
  <p>This provides a correctly formatted query but is of course prone to SQL injections and the like and, as such, is not an acceptable method of achieving my goal. </p>
  
  <p>In other queries I am using the <a href="http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries" rel="nofollow noreferrer">recommended</a> methods of query construction when handling a known number of variables (<code>%s</code> and separate argument to <code>.execute()</code> containing variables) but I'm unsure how to adapt this to accommodate an unknown number of variables without using string formatting.</p>
  
  <p>How can I elegantly and <em>safely</em> construct a query with an unknown number of specified insert columns?</p>