📜  Python - 字典中键的分组层次结构拆分

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

Python - 字典中键的分组层次结构拆分

给定一个键由拆分字符连接的字典,任务是编写一个Python程序将字典转换为嵌套和分组的字典。

例子

方法 #1:使用循环 + split()

在此,我们使用 split() 执行拆分键以进行展平的任务。然后使用字典完成键的记忆,该字典将其他类似的嵌套键添加到其嵌套字典中。

Python3
# Python3 code to demonstrate working of
# Group Hierarachy Splits of keys in Dictionary
# Using loop + split()
  
# initializing dictionary
test_dict = {"1-3" : 2, "8-7" : 0, "1-8" : 10, "8-6" : 15}
               
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing split char 
splt_chr = "-"
  
res = dict()
for key, val in test_dict.items():
    ini_key, low_key = key.split(splt_chr)
      
    # check if key already present
    if ini_key not in res:
        res[ini_key] = dict()
      
    # add nested value if present key
    res[ini_key][low_key] = val
  
# printing result
print("The splitted dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of
# Group Hierarachy Splits of keys in Dictionary
# Using defaultdict() 
from collections import defaultdict
  
# initializing dictionary
test_dict = {"1-3" : 2, "8-7" : 0, "1-8" : 10, "8-6" : 15}
               
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing split char 
splt_chr = "-"
  
res = defaultdict(dict)
for key, val in test_dict.items():
    ini_key, low_key = key.split(splt_chr)
      
    # defaultdict eliminates check step
    res[ini_key][low_key] = val
  
# printing result
print("The splitted dictionary : " + str(dict(res)))


输出
The original dictionary is : {'1-3': 2, '8-7': 0, '1-8': 10, '8-6': 15}
The splitted dictionary : {'1': {'3': 2, '8': 10}, '8': {'7': 0, '6': 15}}

方法 #2:使用defaultdict()

与上述方法类似,唯一的区别是 defaultdict() 用于记忆分组键的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Group Hierarachy Splits of keys in Dictionary
# Using defaultdict() 
from collections import defaultdict
  
# initializing dictionary
test_dict = {"1-3" : 2, "8-7" : 0, "1-8" : 10, "8-6" : 15}
               
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing split char 
splt_chr = "-"
  
res = defaultdict(dict)
for key, val in test_dict.items():
    ini_key, low_key = key.split(splt_chr)
      
    # defaultdict eliminates check step
    res[ini_key][low_key] = val
  
# printing result
print("The splitted dictionary : " + str(dict(res)))
输出
The original dictionary is : {'1-3': 2, '8-7': 0, '1-8': 10, '8-6': 15}
The splitted dictionary : {'1': {'3': 2, '8': 10}, '8': {'7': 0, '6': 15}}