繁体   English   中英

基于公共键和列值将字典键写入 csv 文件

[英]Writing dictionary keys to a csv file based on common key and column value

我有两个需要加入的 CSV 文件。 一个文件包含我想要的部分信息。 我从 CSV 1 创建了我需要的信息字典,并且需要将该字典写入 CSV 2。我想将字典的键写入 CSV 中的相应 ID

如何将字典写入 CSV2? 我的代码用相同的值填充宠物列的每个条目。

提供字典示例,CSV2 和 output CSV 以提供代码的可解释性。

下面的代码

Dictionary
{'511': 'Dog', '611': 'Cat'}

CSV
ID,   Location,   Country
511,  Stack,      USA
611,  Overflow    Mexico 
711,  Stack       USA

Expected CSV
ID,   Location,    Country,    Pet
511,  Stack,       USA,        Dog
611,  Overflow,    Mexico,     Cat
711,  Stack        USA,  

Output Generated CSV
ID,   Location,    Country,    Pet
511,  Stack,       USA,        Dog
611,  Overflow,    Mexico,     Dog
711,  Stack        USA,        Dog

def readfile(filename):
    global map 
    with open(filename, 'rb') as file:
        map = {}
        reader = csv.reader(file)               
        for row in reader:
            #print row[0]
            key = row[0]
            if key in map:
                pass
            map[key] = row[1:]
    file.close()
    return True
            

#print map.keys()

def writefile(filename):
    Location = 'Location'
    tmpfile = filename + '_tmp.csv'
    
    with open(filename, 'rb') as input:  
        with open(tmpfile,'w+b') as output:
            dreader = csv.DictReader(input, delimiter=',')
            fieldnames = dreader.fieldnames
            fieldnames.append(Location)
            
            print('I am here 1')   
            csvwriter = csv.DictWriter(output,fieldnames, delimiter = ',')
            
            #csvwriter.writeheader()
            try:
                csvwriter.writeheader()

            except AttributeError:
                    headers = []
                    for h in fieldnames:
                        headers.append((h,h))
                        csvwriter.writerow(dict(headers))
            print('I am here 2')
                
            try:
                for row in dreader:
                    for col in row:
                        if col is None: continue
                    s = row[col]
                    if s is not None:
                        row[col] = s.replace('"', '\'').replace('\\','\\\\').strip()
                        if row[col] == "NULL": 
                            row[col] = ''
                        
                        for key,value in map.iteritems():
                            if len(value) == 1 and key == 'ID':
                               pass
                            else:
                                row[Location] = value[0]
                
       # w.writeheader()
                    csvwriter.writerow(row)
                
        #print('I am here')
            except Exception: 
                    print ('Could not write appropriate value')

尝试:

import csv

dic = {"511": "Dog", "611": "Cat"}

with open("in.csv", "r") as f_in, open("out.csv", "w") as f_out:
    reader = csv.reader(f_in)
    writer = csv.writer(f_out)
    headers = next(reader)
    writer.writerow(headers + ["Pet"])

    for row in reader:
        writer.writerow(row + [dic.get(row[0], "")])

这将创建out.csv内容:

ID,Location,Country,Pet
511,Stack,USA,Dog
611,Overflow,Mexico,Cat
711,Stack,USA,

尝试这个:

import csv
d = {'511': 'Dog', '611': 'Cat'}

with open("temp.csv", "r") as input_file, open("temp1.csv", "w+") as output_file:
    input_csv = csv.DictReader(input_file, delimiter=",")
    output_csv = csv.DictWriter(output_file, fieldnames=input_csv.fieldnames + ["Pet"])
    output_csv.writeheader() and output_csv.writerows({**row, **{"Pet": d.get(row.get("ID"))}} for row in input_csv)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM