我有字典:
Set-StrictMode -Version 1
并且我希望能够输入和搜索包含文本的键(例如“ asdf”),并返回包含这些键及其值的新字典(newdict)。
exampledict = {'asdf':1, 'fasdfx':2, 'basdx':3, 'gasdf':4, 'gbsdf':5}
在python 3.8中哪种方法最有效?
答案 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)