将字典字符串值转换为字典列表的Python程序
给定一个值作为分隔符分隔值的字典,任务是编写一个Python程序将每个字符串转换为字典列表中的不同值。
Input : test_dict = {“Gfg” : “1:2:3”, “best” : “4:8:11”}
Output : [{‘Gfg’: ‘1’, ‘best’: ‘4’}, {‘Gfg’: ‘2’, ‘best’: ‘8’}, {‘Gfg’: ‘3’, ‘best’: ’11’}]
Explanation : List after dictionary values split.
Input : test_dict = {“Gfg” : “1:2:3”}
Output : [{‘Gfg’: ‘1’}, {‘Gfg’: ‘2”}, {‘Gfg’: ‘3’}]
Explanation : List after dictionary values split.
方法:使用循环和split()
以上功能的组合可以解决这个问题。在这种情况下,我们对每个键的值进行拆分,并将其呈现为字典列表中的单独值。
例子:
Python3
# Python3 code to demonstrate working of
# Convert dictionary string values to Dictionaries List
# Using loop
from collections import defaultdict
# initializing dictionary
test_dict = {"Gfg": "1:2:3:7:9", "best": "4:8", "good": "2"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# create empty mesh
temp = defaultdict(dict)
for key in test_dict:
# iterate for each of splitted values
for idx in range(len(test_dict[key].split(':'))):
try:
temp[idx][key] = test_dict[key].split(':')[idx]
# handle case with No value in split
except Exception as e:
temp[idx][key] = None
res = []
for key in temp:
# converting nested dictionaries to list of dictionaries
res.append(temp[key])
# printing result
print("Required dictionary list : " + str(res))
输出:
The original dictionary is : {‘Gfg’: ‘1:2:3:7:9’, ‘best’: ‘4:8’, ‘good’: ‘2’}
Required dictionary list : [{‘Gfg’: ‘1’, ‘best’: ‘4’, ‘good’: ‘2’}, {‘Gfg’: ‘2’, ‘best’: ‘8’}, {‘Gfg’: ‘3’}, {‘Gfg’: ‘7’}, {‘Gfg’: ‘9’}]