1

Input

dict = {
    "samp1": "x",
    "samp2": "x",
    "exp1": "x"
}

ex = dict((k, v) for k, v in dict.items() if k in samp+str(range(1,10)))

Expected Output

ex = {
    "samp1":"x",
    "samp2":"x"
}

My code get error in this line str(range(1,10)).

How can do like this if k in samp1 samp2 samp3...samp10 ?

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
Jim
  • 87
  • 1
  • 7

4 Answers4

2

Just to point out what's wrong in your code, I have tried to modify min. Try this (One using f-string and dict-comprehension):

dict={
    "samp1":"x",
    "samp2":"x",
    "exp1":"x"
}
li = [F"samp{i}" for i in range(1,11)]
ex = {k:v for k, v in dict.items() if k in li}
print(ex)

Output:

{'samp1': 'x', 'samp2': 'x'}

Another one (Thanks to @OlvinRoght for isDecimal.):

dict = {
    "samp1":"x",
    "samp2":"x",
    "samp12":"x",
    "samp":"x",
    "sampxyz":"x",
    "exp1":"x"
}
ex = {k:v for k, v in dict.items() if k.startswith("samp") and k[4:].isdecimal() and (0 < int(k[4:]) <= 10) }
print(ex)

Output:

{'samp1': 'x', 'samp2': 'x'}
abhiarora
  • 9,743
  • 5
  • 32
  • 57
1

I'd suggest to use re.match here to check if a key begins with the specified pattern:

import re
{k:v for k, v in d.items() if re.match(r'^samp[0-9]', k)}
# {'samp1': 'x', 'samp2': 'x'}

Alternatively you can use startswith, which can also take a tuple:

m = tuple(['samp'+str(i) for i in range(10)],)
{k:v for k, v in d.items() if k.startswith(m)}
# {'samp1': 'x', 'samp2': 'x'}
yatu
  • 86,083
  • 12
  • 84
  • 139
1

Try this below:

ex = {}
for obj in dict:
    if obj.startswith('samp'):
        ex[obj] = dict[obj]
print(ex)
Abhishek Kulkarni
  • 1,747
  • 1
  • 6
  • 8
0

With filter and regexp:

import re

idict = { 
    "samp1": "x",
    "samp2": "x",
    "exp1": "x" 
}

MATCH = re.compile(r'samp[1-9]')
odict = dict(filter(lambda kv: MATCH.fullmatch(kv[0]), idict.items()))
print(odict)

Update: If the number of keys is always low like in the question, it might be more efficent to retrieve just those few keys (if present, of course). Something like:

mykeys = ["samp1", ..., "samp9"]
odict = {key: idict[key] for key in mykeys if key in idict}
VPfB
  • 14,927
  • 6
  • 41
  • 75