【问题标题】:Why the parsed dicts are equal while the pickled dicts are not?为什么解析的字典相等而腌制的字典不相等?
【发布时间】:2023-01-19 03:04:25
【问题描述】:

我正在开发一个聚合配置文件解析工具,希望它能支持.json.yaml.toml文件。所以,我做了下一个测试:

example.json 配置文件如下:

{
  "DEFAULT":
  {
    "ServerAliveInterval": 45,
    "Compression": true,
    "CompressionLevel": 9,
    "ForwardX11": true
  },
  "bitbucket.org":
    {
      "User": "hg"
    },
  "topsecret.server.com":
    {
      "Port": 50022,
      "ForwardX11": false
    },
  "special":
    {
      "path":"C:\\Users",
      "escaped1":"\n\t",
      "escaped2":"\\n\\t"
    }  
}

example.yaml 配置文件如下:

DEFAULT:
  ServerAliveInterval: 45
  Compression: yes
  CompressionLevel: 9
  ForwardX11: yes
bitbucket.org:
  User: hg
topsecret.server.com:
  Port: 50022
  ForwardX11: no
special:
  path: C:\Users
  escaped1: "\n\t"
  escaped2: \n\t

example.toml 配置文件如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = true
CompressionLevel = 9
ForwardX11 = true
['bitbucket.org']
User = 'hg'
['topsecret.server.com']
Port = 50022
ForwardX11 = false
[special]
path = 'C:\Users'
escaped1 = "\n\t"
escaped2 = '\n\t'

然后,带有输出的测试代码如下:

import pickle,json,yaml
# TOML, see https://github.com/hukkin/tomli
try:
    import tomllib
except ModuleNotFoundError:
    import tomli as tomllib

path = "example.json"
with open(path) as file:
    config1 = json.load(file)
    assert isinstance(config1,dict)
    pickled1 = pickle.dumps(config1)

path = "example.yaml"
with open(path, 'r', encoding='utf-8') as file:
    config2 = yaml.safe_load(file)
    assert isinstance(config2,dict)
    pickled2 = pickle.dumps(config2)

path = "example.toml"
with open(path, 'rb') as file:
    config3 = tomllib.load(file)
    assert isinstance(config3,dict)
    pickled3 = pickle.dumps(config3)

print(config1==config2) # True
print(config2==config3) # True
print(pickled1==pickled2) # False
print(pickled2==pickled3) # True

所以,我的问题是,既然解析出来的obj都是dict,而且这些dict是相等的,为什么他们的pickled代码不一样,即为什么从@987654333解析出来的dict的pickled代码@与其他两个不同?

提前致谢。

【问题讨论】:

    标签: json python-3.x yaml toml


    【解决方案1】:
    【解决方案2】:

    您是否评估了正在创建的数据类型?可能混合了 str 和 int dtypes。祝你好运!

    【讨论】:

    • 这里没有“dtypes”(这不使用numpy)。虽然它是可能的对于导致此结果的不同类型,strint 永远不会是罪魁祸首(它们永远不会相互比较)。无论如何,这实际上并没有回答问题,只是推测可能的原因。一旦你有足够的代表,你可以随心所欲地发表评论,但答案需要尝试回答问题,而不仅仅是猜测。
    猜你喜欢
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多