本文介绍了将文件转换为键/值字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我是否正在创建一个新的字典。我想要一个文件,目前有两个单词用逗号分隔,每一行,并把它变成一个字典,第一个单词是关键字,第二个是值。我看到,如果我打印,这些单词是分开的,但我不确定是否正确返回。谢谢

I am unsure if what I have is actually creating a new dictionary. I want to take a file that currently has two words separated by commas on each line and turn it into a dictionary with the first word being the key and the second being the value. I see that if I print, the words are separated but I am unsure if it is returned correctly. Thanks

WDictionary = open('file.csv', 'r')
for line in WDictionary:
    mylist = line.split(',')
    return mylist


推荐答案

dict(line.split(',') for line in WDictionary)

编辑:建议

dict(line.strip().split(',') for line in WDictionary)

这篇关于将文件转换为键/值字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:35