Reputation: 1924
Code
def fill_dictionary_with_valid_addr_row_data( df ):
data_list = []
dictionary = {}
int_endianness = 0
for i in df.index:
addrstr = str(df['Address'][i])
if (addrstr != 'nan'):
try:
addr = int(addrstr, 16)
except:
print("Address in excel is not in hex format : %s", addrstr)
sys.exit()
width = int(df['Width'][i])
width = int(width / 8);
endianess = df['Endianess'][i]
if (endianess != 'B') and (endianess != 'L'):
print("ERROR: Register endianess is not B or L");
print("Register : %x, Endianess : %s" % (addr, endianess))
sys.exit()
if endianess == 'B':
int_endianness = 1
data_list.append(addr)
data_list.append(width)
data_list.append(int_endianness)
dictionary[i] = data_list
print(dictionary)
data_list.clear()
print(dictionary)
return dictionary
Problem
When i print dictionary inside for loop, Everything is fine. When i print dictionary outside for loop, all the value(lists) are empty.
Below are the logs
{0: [22216704, 4, 1]}
{0: [22216716, 4, 1], 5: [22216716, 4, 1]}
{0: [22216720, 4, 1], 5: [22216720, 4, 1], 7: [22216720, 4, 1]}
{0: [], 5: [], 38: [], 7: []}
I am a beginner python programmer. I tried to search a lot over internet but I have not found any solution.
Any clues?
Upvotes: 0
Views: 287
Reputation: 16494
Whenever you do dictionary[i] = data_list
, you actually assign a reference of the list to the dictionary entry. Consider the following example:
>>> l = [1,2,3]
>>> d = {}
>>> d["a"] = l
>>> d["b"] = l
>>> d
{'a': [1, 2, 3], 'b': [1, 2, 3]}
>>> l.clear()
>>> d
{'a': [], 'b': []}
As you can see the change to l
is reflected in all dictionary values. What you see in your printed output every time is the same list being assigned to one, two or three dictionary entries respectively. Because it's always the same values, it looks as if you added different lists each time, but that's not true.
What you actually want to do is create a new list for every loop iteration:
for i in df.index:
...
data_list = []
data_list.append(addr)
data_list.append(width)
data_list.append(int_endianness)
dictionary[i] = data_list
or shorter:
dictionary[i] = [addr, width, int_endianness]
Using this code data_list
will contain a new list every iteration, with no connection to the previously defined lists.
Upvotes: 2