[英]Python dictionary search values for keys using regular expression
我正在嘗試實現在 Python 字典中搜索特定鍵值的值(使用正則表達式作為鍵)。
例子:
我有一個 Python 字典,它的值如下:
{'account_0':123445,'seller_account':454545,'seller_account_0':454676, 'seller_account_number':3433343}
我需要搜索鍵為“seller_account”的值? 我寫了一個示例程序,但想知道是否可以做得更好。 主要原因是我不確定正則表達式並遺漏了一些東西(比如我如何為以“seller_account”開頭的鍵設置 re):
#!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
如果您只需要檢查以"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
或以 one_liner 方式:
result = [(key, value) for key, value in my_dict.iteritems() if key.startswith("seller_account")]
注意:對於 python 3.X 的使用,將iteritems()
替換為items()
並且不要忘記為print
添加()
。
您可以使用 dpath 解決此問題。
http://github.com/akesterson/dpath-python
dpath 允許您在鍵上使用 glob 語法搜索字典,並過濾值。 你想要的是微不足道的:
$ easy_install dpath
>>> dpath.util.search(MY_DICT, 'seller_account*')
...這將返回一個包含與該 glob 匹配的所有鍵的大型合並字典。 如果您只想要路徑和值:
$ easy_install dpath
>>> for (path, value) in dpath.util.search(MY_DICT, 'seller_account*', yielded=True):
>>> ... # do something with the path and value
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)]
您可以使用“re”和“filter”的組合。 例如,如果您想在 os 模塊中搜索哪些方法的方法名稱中包含“stat”一詞,您可以使用下面的代碼。
import re
import os
r = re.compile(".*stat.*")
list(filter(r.match, os.__dict__.keys()))
結果是:
['stat', 'lstat', 'fstat', 'fstatvfs', 'statvfs', 'stat_result', 'statvfs_result']
就像我如何為以“seller_account”開頭的鍵設置 re
reObj = re.compile('seller_account')
應該:
reObj = re.compile('seller_account.*')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.