-1

I have a dictionary:

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

and I want to be able to input and search keys that contain a text (par example "asdf"), and return a new dictionary (newdict) with these keys and their values.

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

Which would be the most efficient way to do it in python 3.8 ?

l34rner
  • 1
  • 1
  • 2
    Does this answer your question? [Filter dict to contain only certain keys?](https://stackoverflow.com/questions/3420122/filter-dict-to-contain-only-certain-keys) – mkrieger1 Aug 30 '20 at 22:35

4 Answers4

1

Use dict comprehension:

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)

Prints:

{'asdf': 1, 'fasdfx': 2, 'gasdf': 4}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Thank you, for your prompt response! Sorry to ask again, but If I try to use input in search term does not seem to give the expected result. Can you point out the reason: searchterm = input('Type a searchterm: ') exampledict = {'asdf':1, 'fasdfx':2, 'basdx':3, 'gasdf':4, 'gbsdf':5} newdict = {k: v for k, v in exampledict.items() if 'searchterm' in k} print(newdict) – l34rner Aug 31 '20 at 00:02
  • @l34rner Try `newdict = {k: v for k, v in exampledict.items() if searchterm in k}` Without the `'`. – Andrej Kesely Aug 31 '20 at 04:39
0

Using a dict comprehension:

>>> 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}
Jab
  • 26,853
  • 21
  • 75
  • 114
0

You can use another option like this;

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)
Ahmed Mamdouh
  • 696
  • 5
  • 12
-2

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

#the loop will traverse through the dict , k stands for key and v stands for value

for k ,v in exampledict.items():

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