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 方法对字典中相似的键值对进行分组。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP