Python 程式將 URL 引數轉換為字典項


Python 中實現的一種資料結構,通常稱為關聯陣列,稱為**字典**。字典由一組鍵值對組成。每個鍵值組合對應一個鍵及其相應的鍵值。

在本文中,我們將學習一個 Python 程式,用於將 URL 引數轉換為字典項。

使用的方法

以下是完成此任務的各種方法 -

  • 使用 urllib.parse.parse_qs() 函式

  • 使用 setdefault() 和 re.findall() 函式

  • 使用 split() 函式

示例

假設我們已經獲取了一個包含 URL 引數的**輸入字串**,我們將此查詢字串轉換為如下所示的字典項。

輸入

'tutorials=9&Point=3&Website=2&is=1&best=Yes'

輸出

The parsed URL Params of an input string:  {'tutorials': ['9'], 'Point': ['3'], 'Website': ['2'], 'is': ['1'], 'best': ['Yes']}

使用 urllib.parse.parse_qs() 函式

在此方法中,我們將使用以下預設內建函式來完成此任務;

urllib.parse.parse_qs() function:

它進行解析,鍵從“=”的左側建立,並且它返回一個值列表,這些值是引數的 RHS 值。要使其工作,請匯入外部 urllib.parse()。

演算法(步驟)

以下是執行所需任務應遵循的演算法/步驟 -。

  • 使用 import 關鍵字匯入 urllib.parse 模組。

  • 建立一個變數來儲存**輸入字串**。

  • 列印輸入字串。

  • 透過將輸入字串作為引數傳遞給它,使用**urllib.parse.parse_qs()** 函式。

  • 此處,上述步驟將給定的 URL 引數(查詢字串)轉換為字典項。

  • 列印輸入字串的結果解析的 URL 引數

示例

以下程式使用 urllib.parse.parse_qs() 函式返回給定 URL 引數字串的字典項 -

# importing urllib.parse module
import urllib.parse
# input string
inputString = 'tutorials=9&Point=3&Website=2&is=1&best=Yes'
# printing input string
print("Input String:", inputString)
# Pass the input string to parse_qs(query string) to convert to dictionary
resultParams = urllib.parse.parse_qs(inputString)
# printing resultant parsed URLs params of an input string 
print("The parsed URL Params of an input string: ", resultParams)

輸出

Input String: tutorials=9&Point=3&Website=2&is=1&best=Yes
The parsed URL Params of an input string:  {'tutorials': ['9'], 'Point': ['3'], 'Website': ['2'], 'is': ['1'], 'best': ['Yes']}

使用 setdefault() 和 re.findall() 函式

**re.findall() 函式** - findall() 函式返回字串中模式的所有不重疊匹配項,作為一個字串列表。字串從左到右掃描,並且匹配項按發現的順序返回。

setdefault() 方法

setdefault() 方法返回具有給定鍵的項的值。

如果鍵尚不存在,則使用給定值插入它。

語法

dictionary.setdefault(keyname, value)

演算法(步驟)

以下是執行所需任務應遵循的演算法/步驟 -。

  • 使用 import 關鍵字匯入**re**(正則表示式) 模組。

  • 使用 re 模組的**findall()** 函式,透過將正則表示式模式、字串作為引數傳遞給它,從輸入字串中獲取所有引數。

  • 建立一個新的空字典,用於儲存輸入字串的結果解析的 URL。

  • 使用**for 迴圈**遍歷上述所有引數字典的鍵、值。

  • 使用 [] 運算子和 setdefault 函式將字典的值設定為列表。

  • 使用 append() 函式將此值附加到字典中。

  • 列印輸入字串的結果解析的 URL 引數。

示例

以下程式使用 setdefault() 和 re.findall() 函式返回給定 URL 引數字串的字典項 -

# importing re module
import re
# input string
inputString = 'tutorials=9&Point=3&Website=2&is=1&best=Yes'
# printing input string
print("Input String:", inputString)
# getting all params from input string using regex pattern
all_params = re.findall(r'([^=&]+)=([^=&]+)', inputString)
# Creating a new dictionary to store the URL Parameters as dictionary items
resultantDict = dict()
# traversing through the key, values of above all_params dictionary
for k, v in all_params:
  # Set the value of the dictionary as a list using the [] operator and setdefault function
  # Then append this value to the dictionary 
    resultantDict.setdefault(k, []).append(v)
# printing resultant parsed urls params of input string
print("The parsed urls params of input string:", resultantDict)

輸出

執行後,上述程式將生成以下輸出 -

Input String: tutorials=9&Point=3&Website=2&is=1&best=Yes
The parsed URLs params of an input string: {'tutorials': ['9'], 'Point': ['3'], 'Website': ['2'], 'is': ['1'], 'best': ['Yes']}

使用 split() 函式

在此方法中,我們將使用 split 方法將 URL 引數轉換為字典項。

語法

split():

將字串拆分為列表。我們可以定義分隔符;預設分隔符是任何空格。

示例

以下程式使用 split() 函式返回給定 URL 引數字串的字典項 -

# input string
inputString = 'tutorials=9&Point=3&Website=2&is=1&best=Yes'
# printing input string
print("Input String:", inputString)
# creating an empty dictionary for storing all params
resultantDict = dict()
# splitting input string based on & separator
splittedList = inputString.split("&")
# Traverse in the split list using the for loop
for k in splittedList:
  # Split the list again with "=" separator and store the key and value separately
	p,q=k.split("=")
	# Assign the above key with the list value to the result Dictionary
	resultantDict[p]=[q]
# printing resultant parsed URLs params of the input string 
print("The parsed URLs params of input string:", resultantDict)

輸出

執行後,上述程式將生成以下輸出 -

Input String: tutorials=9&Point=3&Website=2&is=1&best=Yes
The parsed URLs params of an input string: {'tutorials': ['9'], 'Point': ['3'], 'Website': ['2'], 'is': ['1'], 'best': ['Yes']}

結論

在本文中,我們學習瞭如何使用 3 種不同的方法將 URL 引數轉換為字典項。使用 regex.findall() 函式,我們學習瞭如何使用正則表示式分割給定字串。我們學習瞭如何使用 setdefault() 函式將字典的值更改為任何預設值。

更新於: 2023-08-18

1K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告