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() 函数遍历输入字典的键和值对(items()函数返回一个视图对象,即它包含字典的键-值对,作为元组在列表中)。
-
使用 frozenset() 函数将字典的值转换为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方法将字典中相似的键值对分组。