-1

I have dict and need to extract the value starts with '12'. I have wrote the code and working. Can help me writing the code with regex

test = {'name': 'a','num': '1234','num2':'5678', 'num3':'0142'}
[ k for k,v in test.items() if str(v).startswith('12')]

My Out

['num', 'num4']
  • 1
    [Check if string matches pattern](https://stackoverflow.com/questions/12595051/check-if-string-matches-pattern) – SacrificerXY Sep 29 '19 at 05:03
  • 1
    Why do you need to use regex when `startswith` is already doing the job? In what way is it insufficient for your needs (please provide a variety of input and output examples and explain what you need to achieve). Thank you. – ggorlen Sep 29 '19 at 05:17

2 Answers2

0

Your code also works fine. You are printing key instead of value.

test = {'name': 'a','num': '1234','num2':'5678', 'num3':'0142'}
[ v for k,v in test.items() if str(v).startswith('12')]

Output:

['1234']
0
import re

test = {'name': 'a', 'num': '1234', 'num2': '5678', 'num3': '0142'}
[k for k, v in test.items() if re.match('12', v)]
gnvk
  • 1,494
  • 12
  • 14