将项目组合在一起进行字典循环

时间:2016-11-01 02:14:14

标签: python-2.7 dictionary

我无法将ID存储到密钥中,就像子(父子)一样。我花了几个小时就无法找到实现这个目标的方法。我期待的输出是在这篇文章的最后。任何帮助都会很棒。

import sys
import collections

dict = collections.OrderedDict()
dict["A.1"] = {"parent_child":0}
dict["A.1.1"] = {"parent_child":1}
dict["A.1.1.1"] = {"parent_child":2}
dict["A.1.1.2"] = {"parent_child":2}
dict["A.1.1.3"] = {"parent_child":2}
dict["A.1.2"] = {"parent_child":1}
dict["A.1.2.1"] = {"parent_child":2}
dict["A.1.2.2"] = {"parent_child":2}
dict["A.1.2.2.1"] = {"parent_child":3}
dict["A.1.2.2.2"] = {"parent_child":3}
dict["A.1.2.3"] = {"parent_child":2}
dict["A.1.3"] = {"parent_child":1}
dict["A.1.4"] = {"parent_child":1}


print(dict)

new_dict = {}

p = 0 # previous index
i = 0 # current
n = 1 # next index

current_PC = 0 # current parent_child
next_PC = 0 # next parent_child

previous_id = ""
current_id = "" 
next_id = ""

change_current = True
change = True

lst = []

while(True):
    if change_current:
        current_id = dict.keys()[i]
        current_PC = dict.values()[i]["parent_child"]
        change_current = False

    try:
        next_id = dict.keys()[n]
        next_PC = dict.values()[n]["parent_child"]
    except:
        pass # it will go out of index

    print("KEY {0}".format(current_id))

    if next_PC > current_PC:
        if next_PC - current_PC == 1:
            lst.append(next_PC)
            next_PC += 1
            print("next_PC: {0}".format(next_PC))

    if next_PC == current_PC:
        new_dict[current_id] = lst
        lst = []
        break

print(new_dict)

尝试使输出看起来像这样(以类似的方式),new_dict应该如下所示:

new_dict["A.1"] = ["A.1.1", "A.1.2", "A.1.3", "A.1.4"]
new_dict["A.1.1"] = ["A.1.1.1", "A.1.1.2", "A.1.1.3"]
new_dict["A.1.1.1"] = []
new_dict["A.1.1.2"] = []
new_dict["A.1.1.3"] = []
new_dict["A.1.2"] = ["A.1.2.1", "A.1.2.2", "A.1.2.3"]
new_dict["A.1.2.1"] = []
new_dict["A.1.2.2"] = ["A.1.2.2.1", "A.1.2.2.2"]
new_dict["A.1.2.2.1"] = []
new_dict["A.1.2.2.2"] = []
new_dict["A.1.2.3"] = []
new_dict["A.1.3"] = []
new_dict["A.1.4"] = []

1 个答案:

答案 0 :(得分:1)

这为您提供了所要求的输出。由于我没有在你想要的输出中看到{"parent_child":...},所以我没有继续其他任何事情。

options = ["A.1","A.1.1","A.1.1.1","A.1.1.2","A.1.1.3","A.1.2","A.1.2.1","A.1.2.2","A.1.2.2.1","A.1.2.2.2","A.1.2.3","A.1.3","A.1.4"]


new_dict = {}

for i, key in enumerate(options):
        new_dict[key] = []
        ls = []
        for j, opt in enumerate(options):
            if (key in opt) and (len(opt)-len(key)==2):
                new_dict[key].append(opt)
    print(new_dict)

修改

使用@Ranbir Aulakh的评论

options = ["A.1","A.1.1","A.1.1.1","A.1.1.2","A.1.1.3","A.1.2","A.1.2.1","A.1.2.2","A.1.2.2.1","A.1.2.2.2","A.1.2.3","A.1.3","A.1.4"]


new_dict = {}

for i, key in enumerate(options):
        new_dict[key] = []
        ls = []
        for j, opt in enumerate(options):
            if (key in opt) and (len(opt.split("."))-len(key.split("."))==1):#(len(opt)-len(key)==2):
                new_dict[key].append(opt)
    print(new_dict)