我有一个存储在变量 List_dicts 中的字典项目列表,我必须将上面列表中的选定项目列表写入文件。在我的python函数下面给出:
def write_items(List_dicts,key_list):
#List_dicts contains the list if dicts
#key_list contains the key separated by comma
k_list=key_list.split(',')
write_string=''
for i in k_list:
write_string=write_string+"item['"+i+"'],"
f=open('log.txt','w')
for item in List_dicts:
f.write(write_string[0:len(write_string)-1]) #this should write item['key1'],item['key2'],item['key3']..,item['keyn'] not the value of string 'write_string'
f.close()
无论如何这可能吗?我的灵感来自 SQL 动态执行查询。