[英]How to move sub-dictionary to another dictionary?
I am writing a function that takes 2 strings as inputs and would move a section of the dictionary to another.我正在编写一个 function ,它将 2 个字符串作为输入,并将字典的一部分移动到另一个。
def move(item_to_move, destination):
# do something....
My initial dictionary looks like this.我最初的字典是这样的。
directories = {
'beers': {
'ipa': {
'stone': {}
}
},
'wines': {
'red': {
'cabernet': {}
}
},
'other' : {}
}
I would like to move either a subsection or section of the dictionary to another section.我想将字典的一个小节或一节移动到另一个节。 The sections are represented by each key of the path delimited by a '/'.
这些部分由由“/”分隔的路径的每个键表示。 For example, the inputs for my function would be:
例如,我的 function 的输入将是:
item_to_move='beers/ipa'
destination='other'
move(directories, item_to_move,destination)
The output would be: output 将是:
{
'wines': {
'red': {
'cabernet': {}
},
},
'other' :{
'beers': {
'ipa': {
'stone': {}
} }
},
}
NOTE: I am assuming all input paths for items_to_move are valid.注意:我假设 items_to_move 的所有输入路径都是有效的。
Find the origin's parent dictionary and the target's dictionary, then update the the target's dictionary with the origin's key and value (removing it from the origin's parent):找到源的父字典和目标的字典,然后用源的键和值更新目标的字典(从源的父中删除它):
def move(tree,originPath,targetPath):
originKey = None
for originName in originPath.split("/"):
originParent = originParent[originKey] if originKey else tree
originKey = originName
targetDict = tree
for targetName in targetPath.split("/"):
targetDict = targetDict[targetName]
targetDict.update({originKey:originParent.pop(originKey)})
output: output:
directories = {
'beers': {
'ipa': {
'stone': {}
}
},
'wines': {
'red': {
'cabernet': {}
}
},
'other' : {}
}
move(directories,'beers/ipa','other')
print(directories)
{ 'beers': {},
'wines': { 'red': {'cabernet': {}} },
'other': { 'ipa': {'stone': {}} }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.