Я пытаюсь создать вложенный словарь из некоторых для циклов. Если мой код расположен так:
for figure in problem.figures:
for object in problem.figures[figure].objects:
attribute_dict_A = {}
nested_dict = {}
for k, v in problem.figures[figure].objects[object].attributes.items():
attribute_dict_A[k] = v
attribute_dict_A.update({'object': object})
nested_dict[figure] = attribute_dict_A
print(nested_dict)
Затем на выходе отображается весь цикл, повторяющийся, как показано ниже:
{'A': {'shape': 'square', 'object': 'a', 'fill': 'yes', 'size': 'very large'}}
{'B': {'shape': 'square', 'object': 'b', 'fill': 'yes', 'size': 'very large'}}
{'C': {'shape': 'square', 'object': 'c', 'fill': 'yes', 'size': 'very large'}}
{'1': {'shape': 'pentagon', 'object': 'd', 'fill': 'yes', 'size': 'very large'}}
{'2': {'shape': 'square', 'object': 'e', 'fill': 'yes', 'size': 'very large'}}
{'3': {'shape': 'triangle', 'object': 'f', 'fill': 'yes', 'size': 'very large'}}
{'4': {'shape': 'pac-man', 'object': 'g', 'fill': 'yes', 'size': 'very large'}}
{'5': {'shape': 'star', 'object': 'h', 'fill': 'yes', 'size': 'very large'}}
{'6': {'shape': 'heart', 'object': 'i', 'fill': 'yes', 'size': 'very large'}}
Но если мой код имеет правильный отступ (см. 'print(nested_dict)'
), то он печатает только последнюю итерацию цикла.
Как я могу перебирать цикл, а также хранить все, что мне нужно?
for figure in problem.figures:
for object in problem.figures[figure].objects:
attribute_dict_A = {}
nested_dict = {}
for k, v in problem.figures[figure].objects[object].attributes.items():
attribute_dict_A[k] = v
attribute_dict_A.update({'object': object})
nested_dict[figure] = attribute_dict_A
print(nested_dict)
Мой конечный результат будет следующим:
{'6': {'shape': 'heart', 'object': 'i', 'fill': 'yes', 'size': 'very large'}}
EDIT----
Я обновил свой код до этого, но я все еще не получаю нужный мне результат. Кажется, что он перекрывает мой словарь каждый раз, когда он выполняет итерацию через цикл.
nested_dict = {}
attribute_dict = {}
for figure in problem.figures:
for object in problem.figures[figure].objects:
for k, v in problem.figures[figure].objects[object].attributes.items():
attribute_dict[k] = v
attribute_dict.update({'object': object})
nested_dict[figure] = attribute_dict
pprint(nested_dict)
Вот пример текстового файла, который я просматриваю:
Столб A - это фигура, нижний регистр a - это объект, k, v - пара атрибутов
A
a
shape:circle
size:very large
fill:no
b
shape:plus
size:small
fill:yes
angle:0
inside:a
B
c
shape:circle
size:very large
fill:no
d
shape:plus
size:small
fill:yes
angle:0
inside:c
C
e
shape:circle
size:very large
fill:no
f
shape:plus
size:small
fill:yes
angle:0
inside:e
Затем итерация, создавая словарь, поэтому каждый раз итерации создается новый пустой dict, поэтому nested_dict
из цикла:
nested_dict = {}
for figure in problem.figures:
for object in problem.figures[figure].objects:
attribute_dict_A = {}
for k, v in problem.figures[figure].objects[object].attributes.items():
attribute_dict_A[k] = v
attribute_dict_A.update({'object': object})
nested_dict[figure] = attribute_dict_A
print(nested_dict)
Возможно, Btw может также изменить attribute_dict_A
:
attribute_dict_A = {}
nested_dict = {}
for figure in problem.figures:
for object in problem.figures[figure].objects:
for k, v in problem.figures[figure].objects[object].attributes.items():
attribute_dict_A[k] = v
attribute_dict_A.update({'object': object})
nested_dict[figure] = attribute_dict_A
print(nested_dict)
nested_dict[figure] = attribute_dict_A
кажется, указывает, что attribute_dict_A = {}
был там, где он должен быть. В противном случае attribute_dict_A
будет только расти. Если что-либо назначенное nested_dict[figure] = attribute_dict_A
может быть перемещено вверх на один уровень вложенности
nested_dict
, тогда хорошие вещи случаются.