ich habe ein problem mit dem dynamischen erstellen von Dictionaries aus einer for Schleife heraus.
es bleibt nur das jeweils letzte erzeugte Dictionary erhalten. Ein einfaches Beispiel sieht so aus:
Code: Alles auswählen
a = { 'a1' : '1',
'a2' : '2'}
b = { 'b1' : '3',
'b2' : '4'}
test = {}
anz = 3
test = a.copy()
print('copy of a')
print(test)
test['nb_of_BB'] = anz
for x in range(0, test['nb_of_BB']):
test['BB'] = {}
test['BB'][x] = b.copy()
print('%i. copy of b' %(x+1))
print(test)
print(test['BB'].keys())
Code: Alles auswählen
copy of a
{'a1': '1', 'a2': '2'}
1. copy of b
{'a1': '1', 'a2': '2', 'BB': {0: {'b2': '4', 'b1': '3'}}, 'nb_of_BB': 3}
dict_keys([0])
2. copy of b
{'a1': '1', 'a2': '2', 'BB': {1: {'b2': '4', 'b1': '3'}}, 'nb_of_BB': 3}
dict_keys([1])
3. copy of b
{'a1': '1', 'a2': '2', 'BB': {2: {'b2': '4', 'b1': '3'}}, 'nb_of_BB': 3}
dict_keys([2])
hat jemand eine Idee warum ?
wenn ich die Einträge statisch erzeuge funktioniert es einwandfrei.
Code: Alles auswählen
a = { 'a1' : '1',
'a2' : '2'}
b = { 'b1' : '3',
'b2' : '4'}
test = {}
test = a.copy()
print('copy of a')
print(test)
test['nb_of_BB'] = 3
test['BB'] = {}
test['BB'][0] = b.copy()
print('1. copy of b')
print(test)
test['BB'][1] = b.copy()
print('2. copy of b')
print(test)
print(test['BB'].keys())
test['BB'][2] = b.copy()
print('3. copy of b')
print(test)
print(test['BB'].keys())
Code: Alles auswählen
copy of a
{'a2': '2', 'a1': '1'}
1. copy of b
{'nb_of_BB': 3, 'a2': '2', 'a1': '1', 'BB': {0: {'b2': '4', 'b1': '3'}}}
2. copy of b
{'nb_of_BB': 3, 'a2': '2', 'a1': '1', 'BB': {0: {'b2': '4', 'b1': '3'}, 1: {'b2': '4', 'b1': '3'}}}
dict_keys([0, 1])
3. copy of b
{'nb_of_BB': 3, 'a2': '2', 'a1': '1', 'BB': {0: {'b2': '4', 'b1': '3'}, 1: {'b2': '4', 'b1': '3'}, 2: {'b2': '4', 'b1': '3'}}}
dict_keys([0, 1, 2])