I am trying to implement to search for a value in Python dictionary for specific key values (using regular expression as a key).
Example:
I have a Python dictionary which has values like:
{'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343}
I need to search for values whose key has ‘seller_account’? I wrote a sample program but would like to know if something can be done better. Main reason is I am not sure of regular expression and miss out something (like how do I set re for key starting with ‘seller_account’):
#!usr/bin/python
import re
my_dict={'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343}
reObj = re.compile('seller_account')
for key in my_dict.keys():
if(reObj.match(key)):
print key, my_dict[key]
~ home> python regular.py
seller_account_number 3433343
seller_account_0 454676
seller_account 454545
If you only need to check keys that are starting with
"seller_account", you don’t need regex, just use startswith()or in a one_liner way :
NB: for a python 3.X use, replace
iteritems()byitems()and don’t forget to add()forprint.