2017-03-09 70 views
2

我想創建一個Python dict其成員本身dict秒,他們兩個是一樣的:如何定義一個具有相同值的多個子字典的Python字典?

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服務器定義,但我不希望不得不重複一遍 - 有沒有辦法做到這一點?

+0

在一條語句中無法 – timgeb

+0

讓我們做一些改變,我的演示配置=>'服務器[「示範」] [「client_secret」] =「foo'' =>進入的堆棧溢出問題,」我的測試服務器突然失敗而沒有改變,爲什麼?「我真的不認爲複製粘貼是一件壞事。 – polku

+0

你能先用測試和活鍵創建字典嗎?然後,只需更新與演示作爲關鍵字和測試爲值例如:'servers.update({'demo':servers ['test']})' –

回答

0
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

+0

是的,當然我可以做到這一點;我想知道在「服務器」本身的定義中是否有辦法做到這一點。 –

+0

「我該如何做X?」 「像這樣」「當然就是這樣,我實際上是在問一個不同的問題,但保持它的祕密,因爲原因」 – TessellatingHeckler

0
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'] 
+0

請注意,更改爲「測試」會自動更新「演示」,反之亦然。 – CaptainKinematics

相關問題