Python dictionary search values for keys using regular expression

前端 未结 3 750
我寻月下人不归
我寻月下人不归 2021-01-31 16:15

I am trying to implement to search for a value in Python dictionary for specific key values (using regular expression as a key).

Example:

I have a Python dictio

相关标签:
3条回答
  • 2021-01-31 16:32

    You can solve this with dpath.

    http://github.com/akesterson/dpath-python

    dpath lets you search dictionaries with a glob syntax on the keys, and to filter the values. What you want is trivial:

    $ easy_install dpath
    >>> dpath.util.search(MY_DICT, 'seller_account*')
    

    ... That will return you a big merged dictionary of all the keys matching that glob. If you just want the paths and values:

    $ easy_install dpath
    >>> for (path, value) in dpath.util.search(MY_DICT, 'seller_account*', yielded=True):
    >>> ... # do something with the path and value
    
    0 讨论(0)
  • 2021-01-31 16:38

    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.

    0 讨论(0)
  • 2021-01-31 16:42
    def search(dictionary, substr):
        result = []
        for key in dictionary:
            if substr in key:
                result.append((key, dictionary[key]))   
        return result
    
    >>> my_dict={'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343}
    >>> search(my_dict, 'seller_account')
    [('seller_account_number', 3433343), ('seller_account_0', 454676), ('seller_account', 454545)]
    
    0 讨论(0)
提交回复
热议问题