Home > Back-end >  Search dictionary keys with regex
Search dictionary keys with regex

Time:11-12

I have defined a dictionary with string keys:

{'dummy': 0, 'K1::foo(bar::z(x,u))': 1, 'K2::foo()': 2}

I want to search for key pattern (not the exact word), so if 'foo' in my_dict: should return true.

yax = 'foo'
if yax in my_dict:
    # Should definitely go here
    value = my_dict[yax]
    print(value)
else:
    # Just for error checking that the given name doesn't exist in dictionary
    print("Given value does not exist")

But the above code goes to the else section.

In the example, foo exists in two keys. That doesn't matter. the first match is OK. As another example, if I search for bar, the if statement should be true, too.

CodePudding user response:

First, know that it is not a good approach to have to search through dictionary keys. The purpose of a dictionary is to enable O(1) access to the values using hashed keys.

That said, you can loop over the keys.

Searching any substring:

d = {'dummy': 0, 'K1::foo(bar::z(x,u))': 1, 'K2::foo()': 2}

[k for k in d if 'foo' in k]

Searching an independent word:

import re
[k for k in d if re.search(r'\bfoo\b', k)]

output: ['K1::foo(bar::z(x,u))', 'K2::foo()']

as dictionary comprehension:

{k:v for k,v in d.items() if 'foo' in k}

output: {'K1::foo(bar::z(x,u))': 1, 'K2::foo()': 2}

  • Related