[英]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.