Python程式合併具有相同值的鍵


Python 中對更常見地稱為關聯陣列的資料結構的實現是字典。字典由一組鍵值對組成。每個鍵值組合對應一個鍵及其對應的值。

在本文中,我們將學習如何在 python 中連線所有具有相似值的鍵。

使用的方法

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

  • 使用 defaultdict() 和 join() 函式

  • 使用字典推導式、groupby() 和 join() 函式

示例

假設我們已經獲取了一個輸入字典。我們現在將使用上述方法連線所有具有相似值的鍵(不包括順序)。

輸入

inputDict = {'hello': {2, 8, 6}, 'tutorialspoint' − {6,7,5}, 'all': {8, 2, 6}, 'users': {5, 6, 7}, 'python'− {10, 1, 9}}

輸出

{'hello-all': frozenset({8, 2, 6}), 'tutorialspoint-users' − frozenset({5, 6, 7}), 'python'− frozenset({1, 10, 9})}

在此輸入字典中,鍵'hello'、'all'具有相同的值得{2, 8, 6}{8, 2, 6}(不包括順序)。因此,它們使用連字元 (-) 連線在一起。

類似地,鍵'tutorialspoint''users'也具有相同的值。因此,它們也分組在一起。

方法 1 使用 defaultdict() 和 join() 函式

defaultdict() - 它是字典的子類,返回一個類似字典的物件。就功能而言,字典和 defaultdict 之間唯一的區別是 defaultdict 永遠不會引發KeyError。如果鍵不存在,它提供一個預設值。

語法

defaultdict(default_factory)

  • default_factory - 它是一個返回字典預設值的函式。如果缺少此引數,則字典會引發 KeyError。

join() - join() 是 Python 中的一個字串函式,用於連線用字串分隔符分隔的序列元素。此函式連線序列元素以轉換為字串

演算法(步驟)

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

  • 使用 import 關鍵字從 collections 模組匯入defaultdict

  • 建立一個變數來儲存輸入字典

  • 列印輸入字典。

  • 建立一個預設字典來儲存雜湊值。

  • 使用 for 迴圈遍歷輸入字典的鍵值對,使用items()函式(返回一個檢視物件,即它包含字典的鍵值對,作為列表中的元組)。

  • 使用frozenset()函式(一個內建函式,返回一個用指定可迭代物件中的元素初始化的不可變 frozenset 物件)將字典的值轉換為 frozenset。

  • 將此值與鍵一起新增到雜湊值中。

  • 遍歷 hashValues 字典,並使用 join() 函式將相似的鍵用“-”作為分隔符連線。

  • 在連線所有具有相似值的鍵後,列印結果字典。

示例

以下程式在使用 defaultdict() 和 join() 函式的輸入字典中連線所有具有相似值的鍵後,返回一個字典 -

# importing defaultdict from the collections module
from collections import defaultdict
# input dictionary
inputDict = {'hello': {2, 8, 6}, 'tutorialspoint': {6, 7, 5}, 'all': {
    8, 2, 6}, 'users': {5, 6, 7}, 'python': {10, 1, 9}}
# printing input dictionary
print("Input dictionary:\n", inputDict)
# Creating a default dictionary to store hash values
hashValues = defaultdict(list)
# travsering through the key, value pairs of input dictionary
for key, value in inputDict.items():
    # Convert values of the dictionary to frozenset and append this key to hashValues
    hashValues[frozenset(value)].append(key)
# joining the key having similar values with hyphen(-)
ouputDict = {'-'.join(keys): values for (values, keys) in hashValues.items()}
# printing resultant dictionary
print("Resultant dictionary after concatenating all keys having similar values:\n", ouputDict)

輸出

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

Input dictionary:
 {'hello': {8, 2, 6}, 'tutorialspoint': {5, 6, 7}, 'all': {8, 2, 6}, 'users': {5, 6, 7}, 'python': {1, 10, 9}}
Resultant dictionary after concatenating all keys having similar values:
 {'hello-all': frozenset({8, 2, 6}), 'tutorialspoint-users': frozenset({5, 6, 7}), 'python': frozenset({1, 10, 9})}

方法 2 使用字典推導式、groupby() 和 join() 函式

itertools.groupby() 函式

將相似型別的物件分組到迭代器物件中。

可迭代物件中每個元素的鍵由此函式確定。

語法

 itertools.groupby(iterable, key_func)

引數

  • iterable - 它類似於列表、字典元組等的可迭代物件。

  • key_func - 它是一個為可迭代物件中的每個元素計算鍵的函式。

返回值 - 返回鍵和分組專案的可迭代物件。如果未給出鍵,則預設使用標識函式。

sorted() 函式

它返回給定可迭代物件的排序列表。

您可以選擇升序或降序。數字按數字排序,而字串按字母順序排列。

語法

 sorted(iterable, key=key, reverse=reverse)

引數

  • iterable - 它是一個序列。

  • key - 將執行以確定順序的函式。預設值為 None

  • reverse - 布林表示式。True 按升序排序,False 按降序排序。預設值為 False

示例

以下程式在使用字典推導式、groupby() 和 join() 函式的輸入字典中連線所有具有相似值的鍵後,返回一個字典 -

# importing groupby from itertools module
from itertools import groupby
# input dictionary
inputDict = {'hello': {2, 8, 6}, 'tutorialspoint': {8, 6, 2}, 'all': {
    2, 4, 3}, 'users': {2, 3, 4}, 'python': {10, 1, 9}}
print("Input dictionary:\n", inputDict)
# Traverse in the sorted Dictionary with the key as the value of the dictionary
# Join the similar keys with - as a delimiter using the join() function
# Here similar elements are grouped using the groupby() function
ouputDict = {'-'.join(v): k for k, v in groupby(
    sorted(inputDict, key=inputDict.get), key=lambda i: inputDict[i])}
# printing resultant dictionary
print("Resultant dictionary after concatenating all keys having similar values:\n", ouputDict)

輸出

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

Input dictionary:
 {'hello': {8, 2, 6}, 'tutorialspoint': {8, 2, 6}, 'all': {2, 3, 4}, 'users': {2, 3, 4}, 'python': {1, 10, 9}}
Resultant dictionary after concatenating all keys having similar values:
 {'hello-tutorialspoint': {8, 2, 6}, 'all-users': {2, 3, 4}, 'python': {1, 10, 9}}

結論

在本文中,我們研究了兩種不同的方法來連線所有具有相似值的鍵。我們還學習瞭如何使用 groupby 方法對字典中相似的鍵值對進行分組。

更新於: 2023年8月18日

61 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告