Python 字典或 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33169404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:55:34  来源:igfitidea点击:

Python Dictionary or JSON

pythonjson

提问by bordeltabernacle

Is there any benefit to converting a large nested Python dictionary to JSON for using within a small library (ie. not over the web)?

将大型嵌套 Python 字典转换为 JSON 以在小型库中使用(即不在网络上)有什么好处吗?

I am parsing configuration files and storing different bits of data for retrieval and output later. Currently all the information is stored in a nested dict, with lists in there also. It's not that there's a problem with this method necessarily, I just wonder if it's beneficial to use a standard data format, and the nested dict looks an awful lot like JSON.

我正在解析配置文件并存储不同的数据位以供稍后检索和输出。目前所有的信息都存储在一个嵌套的字典中,其中也有列表。这种方法不一定有问题,我只是想知道使用标准数据格式是否有益,并且嵌套的dict看起来非常像JSON。

采纳答案by jfs

It is apples vs. oranges comparison: JSON is a data format (a string), Python dictionary is a data structure (in-memory object).

这是苹果与橙子的比较:JSON 是一种数据格式(字符串),Python 字典是一种数据结构(内存对象)。

If you need to exchange data between different (perhaps even non-Python) processes then you could use JSON format to serializeyour Python dictionary.

如果您需要在不同(甚至可能是非 Python)进程之间交换数据,那么您可以使用 JSON 格式来序列化您的 Python 字典。

The text representation of a dictionary looks like (but it is not) json format:

字典的文本表示看起来像(但不是)json 格式:

>>> print(dict(zip('abc', range(3))))
{'a': 0, 'b': 1, 'c': 2}

Text representation (a string) of an object is not the object itself (even string objects and their text representations are different things e.g., "\n"is a single newline character but obviously its text representation is several characters).

对象的文本表示(字符串)不是对象本身(即使字符串对象和它们的文本表示也是不同的东西,例如,"\n"是单个换行符,但显然它的文本表示是几个字符)。

回答by vijay

Yes there is benefit, With json you can play with data and make it look simple, instead of unnecessarily complicating data with '['brackets

是的,有好处,使用 json 您可以处理数据并使其看起来简单,而不是用'['括号将数据不必要地复杂化

well you are right python dictionarysucks and makes code dirty to look

好吧,你是对的python 字典很烂,让代码看起来很脏

Also I am using this json wrapperinstead of dictionary in my python project

另外我在我的 python 项目中使用这个 json 包装器而不是字典

Also if you are worried about performance dictionary vs jsonthen there is no difference.You can use json

另外,如果您担心性能字典与 json则没有区别。您可以使用 json

So my code looks clean with json

所以我的代码用 json 看起来很干净