拆分字典中的列表以创建新的字典可以通过以下步骤实现:
以下是一个示例代码,演示如何拆分字典中的列表以创建新的字典:
def split_dict(dictionary):
new_dict = {}
for key, value in dictionary.items():
if isinstance(value, list):
for item in value:
if item in new_dict:
new_dict[item].append(key)
else:
new_dict[item] = [key]
return new_dict
# 示例用法
original_dict = {
'fruit': ['apple', 'banana'],
'color': 'red',
'animal': ['cat', 'dog'],
'number': 42
}
result_dict = split_dict(original_dict)
print(result_dict)
输出结果为:
{'apple': ['fruit'], 'banana': ['fruit'], 'cat': ['animal'], 'dog': ['animal']}
在这个示例中,原始字典中的键值对被拆分为新字典中的键值对,其中列表中的每个元素都成为新字典的键,原始字典的键成为新字典的值。如果新字典中已经存在相同的键,则将原始字典的键添加到该键对应的值中,以列表形式存储。
领取专属 10元无门槛券
手把手带您无忧上云