Python字典:在字典中搜索多个键,以创建一个包含它们及其值的新键

时间:2020-08-30 22:21:30

标签: python dictionary search key

我有字典:

Set-StrictMode -Version 1

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

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

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

4 个答案:

答案 0 :(得分:1)

使用字典理解:

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}

答案 1 :(得分:0)

使用字典理解:

>>> exampledict = {'asdf':1, 'fasdfx':2, 'basdx':3, 'gasdf':4, 'gbsdf':5}
>>> {k: v for k, v in exampledict.items() if 'asdf' in k}
{'asdf': 1, 'fasdfx': 2, 'gasdf': 4}

答案 2 :(得分:0)

您可以使用其他类似的选项;

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

newdict = {k: exampledict[k] for k in exampledict if 'asdf' in k}
print(newdict)

答案 3 :(得分:-2)

#您的字典 exampledict = {'asdf':1,'fasdfx':2,'basdx':3,'gasdf':4,'gbsdf':5}

#循环将遍历字典,k代表键,v代表值

对于exampledict.items()中的k,v:

if "asdf" in k:
    print(k,v)