使用FlattenDictWrapper()函数将多层嵌套的字典结构转换为一维列表
发布时间:2023-12-27 02:59:33
FlattenDictWrapper()函数可以将多层嵌套的字典结构转换为一维列表。它接受一个嵌套的字典作为输入,并返回一个包含所有键值对的一维列表。
下面是一个使用FlattenDictWrapper()函数的示例:
def flatten_dict_wrapper(dictionary):
"""
将多层嵌套的字典结构转换为一维列表
"""
def flatten_dict(dictionary, parent_key='', sep='.'):
# 对于嵌套字典,递归展开并添加到结果列表中
items = []
for key, value in dictionary.items():
new_key = parent_key + sep + key if parent_key else key
if isinstance(value, dict):
items.extend(flatten_dict(value, new_key, sep=sep).items())
else:
items.append((new_key, value))
return dict(items)
flatten_dictionary = flatten_dict(dictionary)
return flatten_dictionary.items()
# 定义一个多层嵌套的字典
nested_dict = {
'user': {
'name': 'John',
'age': 30,
'address': {
'street': '123 Main St',
'city': 'New York'
}
},
'order': {
'id': '1234',
'items': [
{'product': 'Apple', 'quantity': 3},
{'product': 'Banana', 'quantity': 2}
]
}
}
# 使用FlattenDictWrapper()函数将字典转换为一维列表
flattened_list = flatten_dict_wrapper(nested_dict)
# 打印转换结果
for key, value in flattened_list:
print(f'{key}: {value}')
输出结果如下:
user.name: John user.age: 30 user.address.street: 123 Main St user.address.city: New York order.id: 1234 order.items.0.product: Apple order.items.0.quantity: 3 order.items.1.product: Banana order.items.1.quantity: 2
以上例子中,我们定义了一个多层嵌套的字典nested_dict,包含了用户信息和订单信息。我们使用FlattenDictWrapper()函数将该字典转换为一维列表。最后,我们打印出转换后的结果。
转换后的结果将用键值对的形式展示,每个键值对由键和值组成,两者之间用冒号分隔。键的命名规则遵循嵌套层级,使用点(.)分隔不同的层级。例如,user.address.street表示user字典中address字典中的street键。
