If you only need to check keys that are starting with "seller_account", you don't need regex, just use startswith()

my_dict={'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343}

for key, value in my_dict.iteritems():   # iter on both keys and values
        if key.startswith('seller_account'):
                print key, value

or in a one_liner way :

result = [(key, value) for key, value in my_dict.iteritems() if key.startswith("seller_account")]

NB: for a python 3.X use, replace iteritems() by items() and don't forget to add () for print.

Answer from Cédric Julien on Stack Overflow
🌐
GitHub
github.com › LumenTheFairy › regexdict
GitHub - LumenTheFairy/regexdict: Python implementation of efficient regex keyed dictionaries · GitHub
regexdict solves this problem by reducing the entire lookup to a single regular expression, which is compiled on construction, and used to match any key. The grouping information from this match allows it to recover the original pattern that ...
Author   LumenTheFairy
Discussions

python - Good and pythonic way to filter list of dictionaries with regular expressions - Stack Overflow
All functionality you're trying to implement already exist in filter(). You pass callable which check condition, it's the most "pythonic" way. ... All your keys in dic have to be strings. More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2021
python - Remove dictionary values based on regex? - Stack Overflow
You've already demonstrated how to filter a dictionary based on a boolean condition, and from that you could easily modify it to use a regex instead. ... @KevinMGranger The exception is the sticking point for me mentally. I would like to filter both keys outside of a pattern specified by regex, ... More on stackoverflow.com
🌐 stackoverflow.com
python - Filtering list of dictionaries by regex match - Stack Overflow
1 Python regex match list but not list with dictionaries · 9 Python - Filter list of dictionaries based on multiple keys More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2013
regular expression dictionary key search - Post.Byes - Bytes
Wow, I really am full of horrid questions today. I have a dictionary with a list of patterns: >>> words = {'sho.':6, '.ilk':8,'.an.':78 } Where the "." character means any pattern - this can easily be changed to the "*" symbol if need be. When the user submits a word, I want to be able to More on post.bytes.com
🌐 post.bytes.com
August 18, 2007
🌐
Finxter
blog.finxter.com › home › learn python blog › how to filter a dictionary in python? (… the most pythonic way)
How to Filter a Dictionary in Python? (... The Most Pythonic Way) - Be on the Right Side of Change
October 9, 2022 - However, by reading this short 8-minute tutorial, you’re going to learn a lot about the nuances of writing Pythonic code. So keep reading! You should always start with the simplest method to solve a problem (see Occam’s razor) because premature optimization is the root of all evil! So let’s have a look at the straightforward loop iteration method to filter a dictionary. ... You want to keep those (key, value) pairs where key meets a certain condition (such as key%2 == 1).
Top answer
1 of 3
1

I wouldn't try to make a function with all of these responsibilities. It will make testing extremely difficult. Instead I would use the simplest list comprehensions possible for each case:

import re

dic = (
    {"name": "Kan",    "number": "2ABC345", "year": 2000},
    {"name": "Jhon",   "number": "2TTC345", "year": 2001},
    {"name": "Louise", "number": "2ABC366", "year": 2001},
    {"name": "Kevin",  "number": "2ABY000", "year": 2002},
)


# So let's say I want the year 2000
year_2000 = [d for d in dic if d["year"] == 2000]

# or the first letter in name be a k
name_k = [d for d in dic if d["name"].startswith("K")]

# or to see if the number starts with 2 and has 7 numbers
starts_2_digits_7 = [d for d in dic if re.match(r"^2\d{6}$", d["number"])]
2 of 3
0

Let's start from a remark that regular expressions operate on strings. So it is good that you corrected your dic so that each dictionary contains strings (initially year was a number).

The first correction that you should made is that re.compile(dic) is wrong. You can compile a pattern, not the dictionary.

And since you execute your pattern once only, there is no need to compile it in advance. It is simpler when you use just the pattern argument (a string).

Your function can be:

def func(dic, pat, key):
    return list(filter(lambda x: re.search(pat, x[key]), dic))

When you want just to print what has been found, it is enough that the function returns the finding and when you call the function the result will be printed.

Try func(dic, '2000', 'year') and func(dic, '^K', 'name'). It should print just what you want.

But an attempt to run func(dic, '2\d{7}', 'number') will return [] (an empty list), since no number in your data sample contains 2 followed by 7 digits.

But you can e.g. run func(dic, '2A[A-Z]{2}', 'number'), i.e. find dictionaries with number containing:

  • '2A',
  • and then 2 letters.

This time you will get:

[{'name': 'Kan', 'number': '2ABC345', 'year': '2000'},
 {'name': 'Louise', 'number': '2ABC366', 'year': '2001'},
 {'name': 'Kevin', 'number': '2ABY000', 'year': '2002'}]

Edit

If you have some elements of your dictionaries other that strings, you can convert them to a string in your function. Change your function to:

def func(dic, pat, key):
    return list(filter(lambda x: re.search(pat, str(x[key])), dic))

and it will work also on non-string elements in your source dictionaries.

🌐
Bytes
bytes.com › home › forum › topic › python
regular expression dictionary key search - Post.Byes
August 18, 2007 - I know the normal way is to provide the reg exp and search the dictionary with it, but this is the other way round :( Thanks The '$' is the "end of string" operator:[CODE=python] >>> import re >>> reObj = re.compile('.an .$') >>> bool(reObj.matc h("pants")) False >>> bool(reObj.matc h("pant")) True >>> >>> words = ["show", "shoe", "band", "land", "sand", "pant", "pants"] >>> pattDict= {'sho.$':6, '.ilk$':8,'.an.
Find elsewhere
🌐
Python
mail.python.org › pipermail › tutor › 2005-October › 042030.html
[Tutor] Matching dictionary entries by partial key
October 7, 2005 - It documents all the builtin functions ... increase the speed? Yes, compile it outside the loop and use the compiled regex for the match: import re myRe = re.compile('0000|2005') for key in dict: if myRe.match(key): BTW dict is a bad name for a dict, it is the name of the actual ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-substring-key-match-in-dictionary
Python | Substring Key match in dictionary - GeeksforGeeks
April 27, 2023 - ... # Python3 code to demonstrate working of # Substring Key match in dictionary # Using dict() + filter() + lambda # initializing dictionary test_dict = {'All': 1, 'have': 2, 'good': 3, 'food': 4} # initializing search key string search_key ...
🌐
Online-python
learn.online-python.com › python-how-to › filter-dictionaries
Tutorial
# Different ways to filter dictionaries scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 95} # Filter by value high_scores = {k: v for k, v in scores.items() if v >= 90} print(f"High scores: {high_scores}") # Filter by key names_with_a = {k: v for k, v in scores.items() if k.startswith('A')} print(f"Names starting with A: {names_with_a}") # Filter by key length short_names = {k: v for k, v in scores.items() if len(k) <= 3} print(f"Short names: {short_names}") # Using filter function def is_high_score(item): return item[1] >= 90 high_scores_filter = dict(filter(is_high_score, scores.items())) print(f"Using filter(): {high_scores_filter}")
🌐
Reddit
reddit.com › r/python › can i use a dictionary as part of a regex to simplify a search?
r/Python on Reddit: Can I use a dictionary as part of a regex to simplify a search?
July 30, 2023 -

Say I have a dictionary (in Python 3), that's like this:

fruits = {"red fruit":"apple", "yellow fruit":"banana", "green fruit":"kiwi"}

Then I have a text string like:

I have a red fruit, a carrot, a blueberry, a yellow fruit, two potatoes and three green fruits.

I want to be able to replace "red fruit" with "apple" and so on with the other phrases I use as keys in the dictionary. I realize I can loop through the dictionary with replace functions, but is there a way to do this with a dictionary in one shot? I've seen something like that in other languages: A one line command that can search text for all the keys in a dictionary and replace them with their values.

Is that possible in Python?

🌐
GitHub
gist.github.com › 89465127 › 5776892
python filter a dictionary by keys or values · GitHub
It's actually not filtering by keys or by values, @Lane012. I think he meant that you can either filter before iterating in for (using filter), or after iterating in for, using the 'if'. ... >>> d = {1:11, 2:22, 3:33} >>> d {1: 11, 2: 22, 3: 33} >>> d.iteritems() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute 'iteritems' >>>
🌐
GeeksforGeeks
geeksforgeeks.org › python › filter-list-of-dictionaries-based-on-key-values-in-python
Filter List of Dictionaries Based on Key Values in Python - GeeksforGeeks
July 23, 2025 - Filtering a list of dictionaries based on specific key values is a common task in Python. This becomes useful when working with large datasets or when we need to select certain entries that meet specific conditions. We can do this using list comprehensions, the filter() function, and simple loops. List comprehension is one of the most efficient ways to filter a list. It allows us to create a new list by iterating over an existing list and applying a condition.
🌐
sqlpey
sqlpey.com › python › top-4-methods-to-filter-a-python-dictionary-by-keys
Top 4 Methods to Filter a Python Dictionary by Keys - sqlpey
November 23, 2024 - data = {'key1': 1, 'key2': 2, 'key3': 3} allowed_keys = ['key1', 'key2', 'key99'] filtered_data = dict(filter(lambda item: item[0] in allowed_keys, data.items())) print(filtered_data) # Output: {'key1': 1, 'key2': 2} Dictionary Comprehension: A straightforward and Pythonic way.