How to use extract a list of keys with specific pattern from dict in python? -
How to use extract a list of keys with specific pattern from dict in python? -
i need can extract list of keys have type name: carro_x
, x
number. yielding:
lista = ['carro_1','carro_2','carro_50']
from:
diccionario = { 'carro_1':'renault', 'carro_2':'audi', 'carro_50':'sprint', 'camioneta':'tucson' }
how using str.startswith
:
using list comprehension (no need utilize iterkeys
or keys
method; iterating dictionary yeidls keys):
>>> diccionario={ ... 'carro_1':'renault', ... 'carro_2':'audi', ... 'carro_50':'sprint', ... 'camioneta':'tucson', ... } >>> [key key in diccionario if key.startswith('carro_')] ['carro_1', 'carro_50', 'carro_2']
note dictionary has no order. need sort result if want ordered result.
>>> sorted(['carro_1', 'carro_50', 'carro_2'], key=lambda key: int(key.split('_')[1])) ['carro_1', 'carro_50', 'carro_2']
update
to more correct, should take business relationship digits part. utilize str.isdigit
check whether string consist of digits.
>>> [key key in diccionario ... if key.startswith('carro_') , key.split('_', 1)[1].isdigit()] ['carro_1', 'carro_50', 'carro_2']
python list python-2.7 dictionary
Comments
Post a Comment