如何在不使用任何模块或导入CSV的情况下从CSV文件创建字典?

时间:2016-11-09 18:40:37

标签: python csv dictionary

当我收到包含以下内容的CSV文件时

file1 = '"Name","Weight","Height","EyeColor"

"Jimmy","145","160","Blue"

"Kim","120","150","Brown"

"Sean","170","188","Red"'

我的回答应该回复:

{'Jimmy': [(145,160,'Blue')], 'Kim': [(120,150,'Brown')], 'Sean': [(170,188,'Red')]}

enter image description here

我目前的代码,我真的很感激帮助。

3 个答案:

答案 0 :(得分:1)

如果您不想使用任何模块,则可以根据文件的分隔符拆分文件 - 在本例中为,。在这样做时,您将留下数据列表,每个单独的属性都是列表中的元素。

要按照您希望的方式获取dict,我们会使用list切片来分割元素:

csv_dict = {}
for line in open('your_csv_file.csv', 'r').readlines()[1:]:
    line = line.replace('\n', '')
    line = line.split(',')
    csv_dict[line[0]] = line[1:] 

这将为您留下dict,其中名称为键,其他属性为列表中的键值。

答案 1 :(得分:0)

我稍微改变了你的功能。代码如下:

def readf(somefile):
    my_dict = {}
    with open(somefile, 'r') as f:
        for line in f.readlines()[1:]:
            line = line.rstrip()
            line = line.replace('"', '')
            items = line.split(',')
            my_dict[items[0]] = [int(items[1]), int(items[2]), items[3]]
    return my_dict

# print keys in alphabetical order
my_list = list(my_dict.keys())
my_list.sort()
print(my_list)

答案 2 :(得分:0)

In [21]: def readf(somefile):
...:     my_dict = {}
...:     with open(somefile, 'r') as f:
...:         for i, line in enumerate(f):
...:             if i == 0:
...:                 continue
...:             line = line.replace('\"', '')
...:             line = line.replace('\n', '')
...:             items = line.split(',')
...:             key, values = items[0], [(int(items[1]), int(items[2])], items[3])
...:             my_dict[key] = values
...:     return my_dict
...:

In [22]: d = readf('file1')

In [23]: d
Out[23]:
{'Jimmy': [(145, 160, 'Blue')],
 'Kim': [(120, 150, 'Brown')],
 'Sean': [(170, 188, 'Red')]}