python - Python 字典:在字典中搜索多个键以创建一个包含它们及其值的新键
问题描述
我有一本字典:
exampledict = {'asdf':1, 'fasdfx':2, 'basdx':3, 'gasdf':4, 'gbsdf':5}
我希望能够输入和搜索包含文本的键(例如“asdf”),并返回包含这些键及其值的新字典(newdict)。
newdict = {'asdf':1, 'fasdfx':2, 'gasdf':4}
在 python 3.8 中哪一种是最有效的方法?
解决方案
使用 dict 理解:
exampledict = {'asdf':1, 'fasdfx':2, 'basdx':3, 'gasdf':4, 'gbsdf':5}
newdict = {k: v for k, v in exampledict.items() if 'asdf' in k}
print(newdict)
印刷:
{'asdf': 1, 'fasdfx': 2, 'gasdf': 4}
推荐阅读
- django - 为两种不同的用户类型(客户、供应商)扩展抽象用户模型
- r - 调整以便正确生成表格
- reactjs - 空检查后对象可能为“空”
- reactjs - 使用 react router dom v6 保护路由 渲染没有返回任何内容
- c++ - 如何从我的函数中获取 TSP 导览?
- python - Python 子进程 - 进入伪终端以将命令作为 args 或作为输入流运行到远程 ssh 终端
- python - 获取 Python 中不和谐机器人的不和谐显示名称的括号部分
- android - "建议:添加 'tools:replace="android:value"' 到
AndroidManifest.xml:12:9-14:91 中的元素覆盖。” - maven - 如何禁用连接到 Maven 中心的 Maven
- javascript - Stripe API 问题的 Ruby 结帐按钮?