[英]Python - Find key in dictionary using regex
我有一個無法更改的固定字典,需要在不知道鍵中空格數量的情況下找到正確的鍵。 這是我所擁有的:
mydict = dict(
'entry 1'='first',
'entry 2'='second',
# ...
'entry 10'='tenth',
# ...
)
我需要根據“數字”找到正確的條目,例如mydict[entry 4]
,但不知道單詞entry
和數字之間有多少空格。 知道如何實現這一目標嗎?
我會假設我可以使用一些聰明的正則表達式,它允許在entry
和數字之間使用任意數量的字符,但空格是唯一允許的字符。
這個正則表達式解決方案應該適合你。
import re
# fixed pre-given dictionary
mydict ={
'entry 1':'first',
'entry 2':'second',
'entry 4' : 'fourth',
'entry 10':'tenth'}
# the number that you have been given; in your example, 4
num = 4
#loop through the keys and values of the dictionary
for key, val in mydict.items():
# use regex to find all integers in the key. Ignores the whitespace
ints = list(map(int, re.findall(r'\d+', key)))
# if integer in the key, is the number that you have been given
if num in ints:
# then you have found your key and value
print(f'key: {key}\nval: {val}')
它遍歷字典中的每個鍵、值對,並找到以所需數字結尾的鍵。
簡短回答:不,您不能在不知道確切鍵的情況下查詢字典(並保持 O(1) 查詢功能。
選項 1 使用相同的空間,但需要leniar時間,並將您的字典視為列表
for k, v in mydict.items():
if k.startswith("entry") and k.endswith(4): ## or use a regex pattern here
return v
Option2使用輔助數據結構來跟蹤對mydict
的更改並具有更好的空格不敏感鍵。 按比例使用更多 memory,但您會獲得字典的優勢
mydict_index = {}
for k, v in mydict.items():
index_key = k.replace(" ", "")
mydict_index[index_key] = v
請注意,執行選項 2 有更出色的方法,您可以通過將字典包裝在一個中來隱藏您正在使用輔助數據結構的事實。
使用以下正則表達式:
import re
my_number = 14
pattern = r"entry\s+{}".format(my_number)
然后用一些match
來測試你的密鑰,或者search
package 的re
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.