簡體   English   中英

擁有密鑰列表,從dict獲取值的列表/元組

[英]Having list of keys, get list/tuple of values from dict

當我有密鑰列表時,是否有一種簡單,可讀和Pythonic方式從dict中提取特定值?

我經常發現自己這樣做:

uri = "http://%s:%s" % (self.options['listener_port'], self.options['listener_host'])

這是丑陋和漫長的。 我總覺得寫點東西:

uri = "http://%s:%s" % self.options['listener_port', 'listener_host']

應該是可能的,但它無效(至少在Python 2.7中沒有)。

什么是“官方”Pythonic方式?

如果您使用str.format而不是(更老式) %格式,您可以簡單地執行:

"http://{0[listener_port]}:{0[listener_host]}".format(self.options)

在更一般的情況下,您可以從keys列表中獲取dict多個值,例如:

values = [d[key] for key in keys]

並使用*解壓縮,例如

"http://{0}:{1}".format(*(d[key] for key in keys))

但你無法解壓縮到%格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM