How can i prepend to a dicts keys and format it to a string?

Viewed 46

i have a dict as below:

dict = {'settings': {'start_dt': "'201901'",
  'end_dt': "'202104'",
  'schema': 'blob'
 }} 

i would like to achieve the following:

"SET start_dt = '201901';SET end_dt = '202104';SET schema = blob;"

i tried the below but it is not really what i am after

  elem = []
    for k,v in dictt['settings'].items():
        strings = ('SET '+k+' ='+v  )
        print(str('SET ')+k+' ='+v  )
        elem.append(strings)

["SET start_dt ='201901'", "SET end_dt ='202104'", 'SET schema =blob']

how can i achieve desired result?

3 Answers

You can use str.join:

d = {'settings': {'start_dt': "'201901'", 'end_dt': "'202104'", 'schema': 'blob'}}
r = ''.join(f'SET {a} = {b};' for a, b in d['settings'].items())

Output:

"SET start_dt = '201901';SET end_dt = '202104';SET schema = blob;"

Using the below, I seem to get a similar output to your desired. (f-string)

stringFormat = ""
for k,v in dict['settings'].items():
    stringFormat+=f'SET {k} = {v};'

output

"SET start_dt = '201901';SET end_dt = '202104';SET schema = blob;"

You're almost there! You just need join on your elem: ";".join(elem). (However, there are more efficient ways to get it as shown in the other answers.)

Related