简体   繁体   中英

How to use extract a list of keys with specific pattern from dict in python?

I need something that can extract a list of all keys that have the type name: carro_X , where X is a number. Yielding:

lista = ['carro_1','carro_2','carro_50']

from:

diccionario = {
    'carro_1':'renault',
    'carro_2':'audi',
    'carro_50':'sprint',
    'camioneta':'tucson'
}

How about using str.startswith :

Using list comprehension (No need to use iterkeys or keys method; iterating dictionary yeidls keys):

>>> diccionario={
...     'carro_1':'renault',
...     'carro_2':'audi',
...     'carro_50':'sprint',
...     'camioneta':'tucson',
... }
>>> [key for key in diccionario if key.startswith('carro_')]
['carro_1', 'carro_50', 'carro_2']

NOTE Dictionary has no order. You need to sort the result if you 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 be more correct, I should take account the digits part. Use str.isdigit to check whether string consist of digits.

>>> [key for key in diccionario
...     if key.startswith('carro_') and key.split('_', 1)[1].isdigit()]
['carro_1', 'carro_50', 'carro_2']
import re

pattern = re.compile(r'^carro_[0-9]+$')  # !match "SUBMARINE_carro_007Tutti a posto"

key_arr = [key for key in diccionario if pattern.match(key)]

Remember to compile pattern once and reuse it:)

if you only want to get carro X lets edit the dictionnary and use it like that:

carro = {
    1:'renault',
    2:'audi',
    50:'sprint'
}

print carro[50];
print carro[2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM