0

I'm working advent of code 2021 and can't figure out why my code isn't working. The problem is, instead of properly appending the dictionary with only the number at the index the entire number gets appended. When printing out the values being processed everything looks fine, there's the index and the value, but when I check the dictionary all indexes have the entire numbers.

Please do not provide a solution without explaining what went wrong, I'm doing this to learn, not to copy-paste!

Thanks!

test_list = [
'00100',
'11110',
'10110',
'10111',
'10101',
'01111',
'00111',
'11100',
'10000',
'11001',
'00010',
'01010']
test_dict = dict.fromkeys(range(len(test_list[0])),[])

for reading in test_list:
    print(reading)
    for index, bit in enumerate(reading):
        print(index, bit)
        test_dict[index].append(bit)  

Simplified example:

lst = ['four', 'asdf', 'sixy']
dct = dict.fromkeys(range(len(lst[0])),[])
for word in lst: 
    print(word)
    for index, letter in enumerate(word):
        print(index, letter)
        dct[index].append(letter)

Expected result {0:[f,a,s], 1:[o,s,i], 2:[u,d,x], 3:[r,f,y]}. Current result {0:[f,o,u,r,a,s,d,f,s,i,x,y], 1:[f,o,u,r,a,s,d,f,s,i,x,y], ...}

Asrakh
  • 61
  • 1
  • 7
  • You have put the same list in as the value for every key. – khelwood Dec 17 '21 at 22:47
  • Can you provide what kind of result you want ? I can test your code, but guessing the desired output is hard. – Dorian Turba Dec 17 '21 at 22:47
  • @DorianTurba https://adventofcode.com/2021/day/3, basically I want to capture the nth character of each item in a list, so it it should be something like this {0: [0,1,1,1....], 1:[0,1,0,0...], 2:[1,1,1,1,...], etc} The print() for each step looks good, the final dictionary does not. In other words, transpose the list, so the rows become columns and each column will be a a new number. – Asrakh Dec 17 '21 at 22:52
  • Did you understand the issue with your code? – Dorian Turba Dec 17 '21 at 23:02
  • I did understand what went wrong, this seems to be an unintended/weird behaviour, guess I'll either have to manually add the keys, then it works (tested) as .append() doesn't work on an empty dictionary. Will have to look for a way to create an empty dictionary which doesn't rely on dict.fromkeys(). – Asrakh Dec 17 '21 at 23:08
  • The duplicate target explains how to solve this problem. – khelwood Dec 17 '21 at 23:41

0 Answers0