首页 > 解决方案 > Python 字典:在字典中搜索多个键以创建一个包含它们及其值的新键

问题描述

我有一本字典:

exampledict = {'asdf':1, 'fasdfx':2, 'basdx':3, 'gasdf':4, 'gbsdf':5}

我希望能够输入和搜索包含文本的键(例如“asdf”),并返回包含这些键及其值的新字典(newdict)。

newdict = {'asdf':1, 'fasdfx':2, 'gasdf':4}

在 python 3.8 中哪一种是最有效的方法?

标签: pythondictionarysearchkey

解决方案


使用 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}

推荐阅读