Search code examples
pythonpython-3.xstringstring-formatting

Printing list, strings and dict within one string using format in Python3.x


I wish to format a string necessary for querying a database as follows:

SELECT "field1", "field2" FROM "measurement" where "status"=0 AND "node"='name1' LIMIT 10

the following comes from a dict:

  • field1, field2
  • measurement
  • node and name1
  • 10

The dict is as follows:

conf = {
  'fields': ['field1', 'field2'],
  'measurement': 'measurement',
  'limit': 10,
  'tags': {'node': 'name1'}
}

I am able to format the string a part of the string (without the tags) as follows:

    QUERY = 'SELECT "{}" FROM {} WHERE "status"=0 LIMIT {}'.format(
             '","'.join(conf['fields'],
             conf['measurement'],
             conf['limit'])

This provides me:

SELECT "field1", "field2" FROM measurement WHERE "status"=0 LIMIT 10

Problem

The key value pair within the tags is in many case dynamic i.e. there is no previously known key (in this example node)

For the string:

QUERY = 'SELECT {} FROM {} WHERE "status"=0 AND "{}"=\'{}\' LIMIT {}

I wish to fill the string format AND "{}"=\'{}\' dynamically (without prior knowledge of the key value pair within tags

How do I achieve this?

I am not sure if:

QUERY = 'SELECT "{}" FROM {} WHERE "status"=0 AND "{}"=\'{}\' LIMIT {}'.format(
                '","'.join(conf['fields']),
                conf['measurement'],
                **conf['tags'],
                conf['limit']
            )

works as it throws the following SyntaxError:

SyntaxError: positional argument follows keyword argument unpacking

Solution

  • I have created the formatted string using the dictionary conf['tags'] beforehand to make it easier to apply to QUERY

    conf = {
      'fields': ['field1', 'field2'],
      'measurement': 'measurement',
      'limit': 10,
      'tags': {'node': 'name1'}
    }
    
    #Create the string using dictionary
    dict_str = ''.join('"{}"=\'{}\''.format(key,value) for key, value in conf['tags'].items())
    
    #Create the final format string
    QUERY = 'SELECT "{}" FROM "{}" WHERE "status"=0 AND {} LIMIT {}'.format(
                    '","'.join(conf['fields']),
                    conf['measurement'],
                    dict_str,
                    conf['limit']
                )
    print(QUERY)
    

    The output will be

    SELECT "field1","field2" FROM "measurement" WHERE "status"=0 AND "node"='name1' LIMIT 10