我试图实现在Python字典中搜索特定键值的值(使用正则表达式作为键).
例:
我有一个Python字典,其值如下:
{'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343}
Run Code Online (Sandbox Code Playgroud)
我需要搜索其键为'seller_account'的值?我写了一个示例程序,但想知道是否可以做得更好.主要原因是我不确定正则表达式并错过了一些东西(比如我如何设置re以#seller_account'开头):
#!usr/bin/python
import re
my_dict={'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343}
reObj = re.compile('seller_account')
for key in my_dict.keys():
if(reObj.match(key)):
print key, my_dict[key]
~ home> python regular.py
seller_account_number 3433343
seller_account_0 454676
seller_account 454545
Run Code Online (Sandbox Code Playgroud)
Céd*_*ien 37
如果你只需要检查开头的键"seller_account",你不需要正则表达式,只需使用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
Run Code Online (Sandbox Code Playgroud)
或以one_liner方式:
result = [(key, value) for key, value in my_dict.iteritems() if key.startswith("seller_account")]
Run Code Online (Sandbox Code Playgroud)
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)]
Run Code Online (Sandbox Code Playgroud)
小智 7
你可以用dpath解决这个问题.
http://github.com/akesterson/dpath-python
dpath允许您在键上使用glob语法搜索字典,并过滤值.你想要的是微不足道的:
$ easy_install dpath
>>> dpath.util.search(MY_DICT, 'seller_account*')
Run Code Online (Sandbox Code Playgroud)
...这将返回一个与该glob匹配的所有键的大合并字典.如果您只想要路径和值:
$ easy_install dpath
>>> for (path, value) in dpath.util.search(MY_DICT, 'seller_account*', yielded=True):
>>> ... # do something with the path and value
Run Code Online (Sandbox Code Playgroud)
您可以组合使用“re”和“filter”。例如,如果您想搜索 os 模块中哪些方法的方法名称中包含“stat”一词,您可以使用下面的代码。
import re
import os
r = re.compile(".*stat.*")
list(filter(r.match, os.__dict__.keys()))
Run Code Online (Sandbox Code Playgroud)
结果是:
['stat', 'lstat', 'fstat', 'fstatvfs', 'statvfs', 'stat_result', 'statvfs_result']
Run Code Online (Sandbox Code Playgroud)
我认为原始问题中的性能问题是使用“re”模块找到键后的键值搜索。如果密钥的一部分是可以互换的,我们就不能使用“startswith”。所以“re”是一个不错的选择。另外,我使用过滤器来获取所有匹配键的列表并制作它们的列表,以便我们可以使用简单的 [DICT[k] for k in LIST] 返回所有值。