1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Can a regular expression be used as a key in a dictionary?

Discussão em 'Python' iniciado por Stack, Setembro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I want a dictionary where keys are regular expressions:

    d = {'a.*': some_value1, 'b.*': some_value2}
    d['apple']


    I want 'apple' to be matched against the regular expression keys. If there is a complete match with a key/regular-expression then the corresponding value should be returned.

    'apple' matches with the regular expression 'a.*' completely, so some_value1 returns.

    Assume the regular expression keys do not conflict (i.e. two keys should not both match the same string exactly). I'll manually handle that.

    Continue reading...

Compartilhe esta Página