【问题标题】:How to define a Python dict with more than one sub-dict having the same values?如何定义具有多个具有相同值的子字典的 Python 字典?
【发布时间】:2017-03-09 16:24:57
【问题描述】:

我正在尝试创建一个 Python dict,其成员本身就是 dicts,其中两个是相同的:

servers = {
  "test": {
    "auth_token": "some-auth-token",
    "client_id": "some-client-id",
    "client_secret": "some-client-secret",
    "scope": "some-scope"
  },
  "live": {
    "auth_token": "auth-token-for-live",
    "client_id": "client-id-for-live",
    "client_secret": "client-secret-for-live",
    "scope": "scope-for-live"
  },
  "demo": servers["test"] # this doesn't work, but this is what I need
}

我的demo 服务器定义与我的test 服务器定义相同,但我不想重复它——有没有办法可以做到这一点?

【问题讨论】:

  • 不可能在单个语句中
  • 让我们对我的演示配置进行一些更改 => servers['demo']['client_secret'] = 'foo' => 传入堆栈溢出问题“我的测试服务器突然失败而没有更改,为什么?”我真的不认为复制粘贴是一件坏事。
  • 你能先用 test 和 live 键创建 dict。然后只需更新 dict 与 demo 作为键和测试作为值 ex :servers.update({'demo':servers['test']})

标签: python dictionary


【解决方案1】:
x = {
    "auth_token": "some-auth-token",
    "client_id": "some-client-id",
    "client_secret": "some-client-secret",
    "scope": "some-scope"
}

servers = {
  "test": x,

  "live": {
    "auth_token": "auth-token-for-live",
    "client_id": "client-id-for-live",
    "client_secret": "client-secret-for-live",
    "scope": "scope-for-live"
  },

  "demo": x

}

例如https://repl.it/GO6Y/0

【讨论】:

  • 是的,我当然可以这样做;我想知道在servers 本身的定义中是否有办法这样做。
  • “我该如何做 X?” “这样” “当然那样,我实际上是在问一个不同的问题,但由于原因而保密”
【解决方案2】:
servers = {
  "test": {
    "auth_token": "some-auth-token",
    "client_id": "some-client-id",
    "client_secret": "some-client-secret",
    "scope": "some-scope"
  },
  "live": {
    "auth_token": "auth-token-for-live",
    "client_id": "client-id-for-live",
    "client_secret": "client-secret-for-live",
    "scope": "scope-for-live"
  }}

servers['demo'] = servers['test']

【讨论】:

  • 请注意,对“test”的更改会自动更新“demo”,反之亦然。
猜你喜欢
  • 2014-04-27
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 1970-01-01
相关资源
最近更新 更多