Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将dicts键前置并将其格式化为字符串?_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 如何将dicts键前置并将其格式化为字符串?

Python 如何将dicts键前置并将其格式化为字符串?,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我的口述如下: dict = {'settings': {'start_dt': "'201901'", 'end_dt': "'202104'", 'schema': 'blob' }} 我希望实现以下目标: "SET start_dt = '201901';SET end_dt = '202104';SET schema = blob;" "SET start_dt = '201901';SET end_d

我的口述如下:

dict = {'settings': {'start_dt': "'201901'",
  'end_dt': "'202104'",
  'schema': 'blob'
 }} 
我希望实现以下目标:

"SET start_dt = '201901';SET end_dt = '202104';SET schema = blob;"
"SET start_dt = '201901';SET end_dt = '202104';SET schema = blob;"
我试过下面的方法,但这不是我真正想要的

  elem = []
    for k,v in dictt['settings'].items():
        strings = ('SET '+k+' ='+v  )
        print(str('SET ')+k+' ='+v  )
        elem.append(strings)
[“设置开始\u dt='201901'”,“设置结束\u dt='202104'”,“设置模式=blob']


如何才能达到预期效果?

您可以使用
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())
输出:

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

你快到了!你只需要在你的
元素上加入
join
“;”。加入(元素)
。(但是,有更有效的方法可以获得它,如其他答案所示。)

使用下面的方法,我似乎可以获得与您所需的类似的输出。(
f-string

输出

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