Python中将嵌套字典转换为映射元组
嵌套字典是一种分层数据结构,其中值本身被称为字典。它允许在基本字典内存储多个字典。映射元组由元组集合定义,其中各个元组包含成对的值。将一种形式转换为另一种形式意味着将键值对之间的更改设置为元组列表。在 Python 中,我们将使用一些内置函数,例如 `isinstance()`、`extend()`、`append()` 和 `str()` 来将嵌套字典转换为映射元组。
语法
以下语法用于示例:
isintance()
`isinstance()` 是 Python 中一个内置函数,用于检查第一个参数是否是第二个参数的子类或实例。
extend()
`extend()` 是 Python 中一个内置方法,用于在当前列表的末尾添加指定的元素。
append()
`append()` 是 Python 中一个内置方法,它接受一个元素作为输入参数,将其添加到给定列表的末尾。
str()
内置函数 `str()` 通过将参数值转换为值的形式来定义。
使用递归
在下面的示例中,程序使用递归函数来管理一些内置函数——`extend()` 和 `append()`,它们将嵌套字典转换为映射元组。
示例
def dict_mapped_tup(dictionary):
map_tuple = []
for key, value in dictionary.items():
if isinstance(value, dict):
map_tuple.extend((key, subkey, subvalue) for subkey, subvalue in dict_mapped_tup(value))
else:
map_tuple.append((key, value))
return map_tuple
# Create the nested dictionary
nes_dict = {
"key 1": "50",
"key 2": {
"subkey 1": "10",
"subkey 2": "20"
},
"key 3": "60"
}
# Calling function
mapped_tup = dict_mapped_tup(nes_dict)
print(mapped_tup)
输出
[('key 1', '50'), ('key 2', 'subkey 1', '10'), ('key 2', 'subkey 2', '20'), ('key 3', '60')]
使用递归生成器和 `isinstance()`
在下面的示例中,程序使用递归生成器,它充当常规函数,这意味着函数自身正在调用。然后使用内置函数 `isinstance()`,它接受两个参数来检查第一个参数是否是第二个参数的子类。
示例
def dict_mapped_tup(dictionary):
for key, value in dictionary.items():
if isinstance(value, dict):
yield from ((key,) + subkey_value for subkey_value in dict_mapped_tup(value))
else:
yield key, value
# Create the nested dictionary
nested_dict = {
"key1": "100",
"key2": {
"subkey1": "200",
"subkey2": "300",
"subkey3": "400"
},
"key3": "500"
}
# Calling function
map_tuple = list(dict_mapped_tup(nested_dict))
print(map_tuple)
输出
[('key1', '100'), ('key2', 'subkey1', '200'), ('key2', 'subkey2', '300'), ('key2', 'subkey3', '400'), ('key3', '500')]
使用字典操作
在下面的示例中,程序使用字典操作以及列表、元组和 for 循环,遍历给定列表以将嵌套字典转换为映射元组。
示例
# Create the nested dictionary
my_dict = {'Tutorials' : {'x' : 10, 'y' : 20}, 'is' : {'x' : 100, 'y' : 400}, 'good' : {'x' : 80, 'y' : 63}}
# Display the original dictionary
print("Original Dictionary: " + str(my_dict))
# Using dictionary operation
result = [(key, tuple(my_dict[k][key] for k in my_dict)) for key in my_dict['Tutorials']]
# Display the output
print("The Combined dictionary: " + str(result))
输出
Original Dictionary: {'Tutorials': {'x': 10, 'y': 20}, 'is': {'x': 100, 'y': 400}, 'good': {'x': 80, 'y': 63}}
The Combined dictionary: [('x', (10, 100, 80)), ('y', (20, 400, 63))]
结论
我们讨论了解决此问题陈述的各种方法。以上两个示例使用了递归函数,这意味着函数自身正在调用,而第三个示例显示了使用列表和元组的字典操作。这种类型的代码有助于根据数据排列构建逻辑。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP