Python:检查任何列表元素是否是字典中的键 [英] Python: Check if any list element is a key in a dictionary
本文介绍了Python:检查任何列表元素是否是字典中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下代码
all_options = { "1": "/test/1", "2": "/test/2", "3": "/test/3" }selected_options = [ "1", "3" ]
如何从 all_options 中获取键与 selected_options 中的条目匹配的条目?
我开始使用列表推导式,但我被困在最后一个子句上:
final = ()[ final.append(option) for option in all_options if ... ]
谢谢
解决方案
就是这样?
<预><代码>>>>dict((option, all_options[option]) for option in selected_options if option in all_options){'1': '/test/1', '3': '/test/3'}从 Python 2.7 和 3 开始,您可以使用 dict 理解 语法:
{option : all_options[option] for option in selected_options if option in all_options}
或者,如果您只想要这些值:
<预><代码>>>>[all_options[option] for selected_options 中的选项如果 all_options 中的选项]['/test/1', '/test/3']Given the following code
all_options = { "1": "/test/1", "2": "/test/2", "3": "/test/3" }
selected_options = [ "1", "3" ]
How do I get the entries from all_options where the key matches an entry in selected_options?
I started down the path of using a List Comprehension, but I'm stuck on the last clause:
final = ()
[ final.append(option) for option in all_options if ... ]
Thank you
解决方案
Just like this?
>>> dict((option, all_options[option]) for option in selected_options if option in all_options)
{'1': '/test/1', '3': '/test/3'}
From Python 2.7 and 3 onwards, you can use the dict comprehension syntax:
{option : all_options[option] for option in selected_options if option in all_options}
Or if you just want the values:
>>> [all_options[option] for option in selected_options if option in all_options]
['/test/1', '/test/3']
这篇关于Python:检查任何列表元素是否是字典中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文