将python字典的特定键的值打印到CSV文件中

时间:2019-06-21 11:48:09

标签: python csv dictionary

我有如下字典:

> {'Target_Table': 'scott  .  employees',
 'Target_Columns': 'empp_id  last_name  first_name  email  phone_number  JOB_DATE  job_id  salary  commission_pct  manager_id  department_id',
 'Source_Columns': 'emp_id    last_name    first_name    email    phone_number    JOB_DATE    job_id    salary    commission_pct    manager_id    department_id',
 'Source_Table': 'scott  .  employee',
 'where_expr': 'emp_id  =  old_emp_id'}

我必须在不同的行中分别打印 Target_Columns值。到目前为止,它们都是单行打印。 我知道如何分割单词,但是我无法执行它,尤其是在 Target_Columns键的值上。

> 'Target_Columns': 'empp_id  last_name  first_name  email  phone_number  JOB_DATE  job_id  salary  commission_pct  manager_id  department_id'

预期输出:

>     Target Columns

>        empp_id
       last_name 
       first_name
       email 
       phone_number 
       JOB_DATE  ...
with open("proc.txt", 'r') as file:   
    if re.search(r'select|SELECT', file.read()):
        selr = select_stmt.parseString(open('proc.txt').read());
        sd=selr.asDict()
        sdict={k: str(v).strip("[]").replace("'", "").replace(","," ").replace("["," ").replace("]"," ") for k, v in sd.items()}
        val=sdict.values()
        for key in sdict:
            if key=='Target_Columns':
                for value in re.findall(r'\S+', val):
                    print(value)

然后使用CSV,我有这样的想法:我不知道如何整合两者

with open('procfile.csv', 'w') as f: 
    fieldnames = ["Source_Table","Source_Columns","Target_Table","Target_Columns"]
    fieldnames = sorted(set(sd.keys()).union(*[sdict,idict]))
    writer = csv.DictWriter(f, fieldnames, extrasaction='ignore') 
    writer.writeheader()
    writer.writerow(sdict)

2 个答案:

答案 0 :(得分:0)

假设sdict是您在问题开始时提到的词典:

sdict = {'Target_Table': 'scott  .  employees',
         'Target_Columns': 'empp_id  last_name  first_name  email  phone_number  JOB_DATE  job_id  salary  commission_pct  manager_id  department_id',
        }

for key, val in sdict.items():
    if key == 'Target_Columns':
        print(key)
        print("\n".join(val.split()))

答案 1 :(得分:0)

下面

sdict = {'Target_Table': 'scott  .  employees',
         'Target_Columns': 'empp_id  last_name  first_name  email  phone_number  JOB_DATE  job_id  salary  commission_pct  manager_id  department_id',
         }

print('\n'.join(sdict['Target_Columns'].split('  ')))