Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从csv文件中获取dict as dict_Python_Csv_Dictionary - Fatal编程技术网

Python 如何从csv文件中获取dict as dict

Python 如何从csv文件中获取dict as dict,python,csv,dictionary,Python,Csv,Dictionary,您好,我想在我的csv文件中编写一本词典,然后在阅读时将其作为口述返回。我在一些python论坛中搜索了它,还看到了这个“csv dictreader”,但我不知道如何正确使用它,所以我在这里询问。 我想象它是这样的,但这不起作用 x = open('file','w') a = {} a['hi'] = 'yes' x.write(str(a)) x.close x = open('file','r') a = x.read() 然后我想把它作为dict拿回来 print(a['hi])

您好,我想在我的csv文件中编写一本词典,然后在阅读时将其作为口述返回。我在一些python论坛中搜索了它,还看到了这个“csv dictreader”,但我不知道如何正确使用它,所以我在这里询问。 我想象它是这样的,但这不起作用

x = open('file','w')
a = {}
a['hi'] = 'yes'
x.write(str(a))
x.close
x = open('file','r')
a = x.read()
然后我想把它作为dict拿回来

print(a['hi])
我这样做是为了测试它,但我只是得到一个字符串,我需要把它写成一个字符串,因为我不能在csv文件中写dicts,你有什么解决方案可以帮我解决这个问题吗? 谢谢。

您可以使用Python模块

在您的情况下,用法是:

# Write the dict
pickle.dump(a, open("file", "wb"))

# Read the dict
a = pickle.load(open("file", "rb"))
您可以使用Python模块

在您的情况下,用法是:

# Write the dict
pickle.dump(a, open("file", "wb"))

# Read the dict
a = pickle.load(open("file", "rb"))

也许更好的解决方案是使用json fromat而不是csv格式编写文件。使用json.dumps将数据结构(例如带整数的dict of list)转换为json表示(字符串)。然后将其写入一个文件。从文件中读取的内容(带有json表示的字符串)可以使用json转换为数据结构。加载也许更好的解决方案是使用json from而不是csv格式编写文件。使用json.dumps将数据结构(例如带整数的dict of list)转换为json表示(字符串)。然后将其写入一个文件。从文件读取的内容(带有json表示的字符串)可以使用json.loads转换为数据结构