📜  将字典字符串值转换为字典列表的Python程序

📅  最后修改于: 2022-05-13 01:55:43.242000             🧑  作者: Mango

将字典字符串值转换为字典列表的Python程序

给定一个值作为分隔符分隔值的字典,任务是编写一个Python程序将每个字符串转换为字典列表中的不同值。

方法:使用循环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))


输出: