Python - CSV to dict - 密钥中的unicode字符

时间:2018-05-21 16:56:03

标签: python

我将以下csv实现为dict方法:

def csv_to_dict(path):
    res = {}
    with open(path, newline='') as csv_file:
        reader = csv.DictReader(csv_file)
        for row in reader:
            for key, value in row.items():
                if key in res:
                    res[key].append(value)
                else:
                    res[key] = [value]

    return res

除了问题之外,此方法可以按预期工作 如果我采用以下输入.csv

Lfd. Nr.,Parameter 1,Parameter 2
1,2,3
1,2,3

上述功能的输出在MAc OS上:

{'\ufeffLfd. Nr.': ['1', '1'], 'Parameter 1': ['2','2'], 'Parameter 2' : ...

在Windows上,我得到以下输出:

{"u00efu00bbu00bfLfd. Nr.": ['1', '1'], 'Parameter 1': ['2','2'], 'Parameter 2' : ...

如何摆脱第一把钥匙中的这些字符?这些为什么?

期望的输出:

{'Lfd. Nr.': ['1', '1'], 'Parameter 1': ['2','2'], 'Parameter 2' : ...

更新 我的csv文件以utf-8编码。

我也试过(没有成功):

with open(path, newline='', encoding='utf-8') as csv_file:

解决方案基于SO问题的标记链接:

with open(path,"r", newline='',encoding='utf-8-sig') as csv_file

1 个答案:

答案 0 :(得分:-1)

代替变量写 str(键),因为它在函数内部循环内的res [key]中使用