Python Forum
QUERY on Looping and creating lists as items within dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
QUERY on Looping and creating lists as items within dictionaries
#1
I would appreciate some help with this, please...

To summarize my scenario -
My input is an array of numbers wherein
Row1 - [1,2,3]
Row2 - [4,5,6]
Row3 - [7,8,9]
And I am trying to output columns looping through the above rows and need
Col1 - [1,4,7]
Col2 - [2,5,8]
Col3 - [3,6,9]

This is half-way through a program and I am stuck trying to get past this part. Wall
I have some extra code in there as I am currently checking for 9 numbers instead of the above 3 shown for illustration and I am also checking for invalid values, duplicate numbers entered,etc

rowDict = {}
colDict = {}

def checkIfDuplicates(listOfElems):
    ''' Check if given list contains any duplicates '''    
    for elem in listOfElems:
        if listOfElems.count(elem) > 1:
            return True
    return False

for x in range(1,10):
    rowDict["row{0}".format(x)] = input("Enter a row of numbers (1-9) : ")
    if len(rowDict["row{0}".format(x)]) > 9:
        print("Longer than 9 digits!")
        break
    try:
        rowDict["row{0}".format(x)] = [int (y) for y in (rowDict["row{0}".format(x)])]
        print(rowDict["row{0}".format(x)])
    except ValueError:
        print ("Invalid value found!")
        break
    result = checkIfDuplicates(rowDict["row{0}".format(x)])
    if result:
        print('Row contains duplicate vlaues!')
        break

for x in range(0,9):
    for y in range(1,10):
        colDict["column{0}".format(y)] = rowDict["row{0}".format(y)][x]
        
print (rowDict)
print (colDict)
And my output currently looks like this -
Output:
Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] {'row1': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'row2': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'row3': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'row4': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'row5': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'row6': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'row7': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'row8': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'row9': [1, 2, 3, 4, 5, 6, 7, 8, 9]} {'column1': 9, 'column2': 9, 'column3': 9, 'column4': 9, 'column5': 9, 'column6': 9, 'column7': 9, 'column8': 9, 'column9': 9} >>>
I see that I am not able to create a list out of the columns and they are single elements and being over-written as a result.
I have tried to use append but got
Error:
colDict["column{0}".format(y)].append(rowDict["row{0}".format(y)][x]) AttributeError: 'int' object has no attribute 'append'
I would like to understand how I can create a list that contains numbers similar to how I have with 'rows'. Appreciate you reading through the long post and if you can help, that would be great Idea
Reply
#2
If you include an error message you should include the code that generated the error.

Is a dictionary the right thing for organizing this kind of data? Dictionaries work great if you have a key and an attribute, but what are you keys? Right now you are using "rowX", but getting the data out you really want to use an index and are getting around your choice of dictionary by using format to generate keys from integers. Do you have to use a dictionary?

How would you solve this problem if you saved the data in a list of lists, essentially a two dimensional list? You save each row of data in a list and build the matrix as a list of lists. Now transposing the matrix is trivial.

As to your original question. What happens when you do this:
dictionary = {'a':1, 'b':2}
dictionary['a'].append['2']
I get the same error you did. dictionary['a'] is an integer, and you cannot append to an integer. If you are forced to complete this assignment how would you create a dictionary filled with empty lists?
Reply
#3
Thanks, Dean for reading through and helping out with your suggestions.

First up,
(Mar-25-2020, 04:58 AM)deanhystad Wrote: If you include an error message you should include the code that generated the error.

I thought the error included my code which caused it -
colDict["column{0}".format(y)].append(rowDict["row{0}".format(y)][x])
Error:
AttributeError: 'int' object has no attribute 'append'
and it was after trying to replace the below code
colDict["column{0}".format(y)] = rowDict["row{0}".format(y)][x]
while populating the columns.

(Mar-25-2020, 04:58 AM)deanhystad Wrote: Is a dictionary the right thing for organizing this kind of data? Dictionaries work great if you have a key and an attribute, but what are you keys? Right now you are using "rowX", but getting the data out you really want to use an index and are getting around your choice of dictionary by using format to generate keys from integers. Do you have to use a dictionary?
There was not a necessity to create a dictionary but I thought it would be a good opportunity to learn a slightly more complex structure by naming the keys on the fly.
Is this a bad practice? I felt it would be orderly to have row keys named row1,row2 and column keys named col1,col2 while populating the corresponding items as a list of numbers.

(Mar-25-2020, 04:58 AM)deanhystad Wrote: How would you solve this problem if you saved the data in a list of lists, essentially a two dimensional list? You save each row of data in a list and build the matrix as a list of lists. Now transposing the matrix is trivial.
And this is precisely what I ended up doing as I felt I was wasting time with creating dictionaries and trying to append entries to an item list.

Here is my code -
I managed to create a 2D array, with rows containing 9 items and each item containing a list (1-9).
Similarly, I transposed and created a 2D array of columns

rows = []
columns = []
squares = []

totalrows = 9
totalcolumns = 9
totalsquares = 9


def checkIfDuplicates(listOfElems):
    for elem in listOfElems:
        if listOfElems.count(elem) > 1:
            return True
    return False

for x in range(totalrows):
    inputRow = input("Enter a row of numbers (1-9) : ")
    if len(inputRow) > 9:
        print("Longer than 9 digits!")
        #break
    try:
        inputList = [int (y) for y in inputRow]
        
        print(inputList)
    except ValueError:
        print ("Invalid value found!")
        #break
    result = checkIfDuplicates(inputList)
    if result:
        print('Row contains duplicate values!')
        #break
    rows.append(inputList)

columns = (list(zip(*[list(i) for i in rows])))

for y in range(totalcolumns):
    result = checkIfDuplicates(columns[y])
    if result:
        print('Column contains duplicate values!')
        #break

print (rows)
print (columns)
And my output is as expected -
Output:
Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Enter a row of numbers (1-9) : 123456789 [1, 2, 3, 4, 5, 6, 7, 8, 9] Column contains duplicate values! Column contains duplicate values! Column contains duplicate values! Column contains duplicate values! Column contains duplicate values! Column contains duplicate values! Column contains duplicate values! Column contains duplicate values! Column contains duplicate values! [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9]] [(1, 1, 1, 1, 1, 1, 1, 1, 1), (2, 2, 2, 2, 2, 2, 2, 2, 2), (3, 3, 3, 3, 3, 3, 3, 3, 3), (4, 4, 4, 4, 4, 4, 4, 4, 4), (5, 5, 5, 5, 5, 5, 5, 5, 5), (6, 6, 6, 6, 6, 6, 6, 6, 6), (7, 7, 7, 7, 7, 7, 7, 7, 7), (8, 8, 8, 8, 8, 8, 8, 8, 8), (9, 9, 9, 9, 9, 9, 9, 9, 9)]
And this takes me to the next step of my problem.
After creating the above rows and column lists, I have to create little 3x3 squares from the rows wherein squares = [[1, 2, 3, 1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6, 4, 5, 6], [7, 8, 9, 7, 8, 9, 7, 8, 9], and so on....]]
which are the first 3 items of row0, row1 & row2, then the next 3 items of row0, row1 & row 2 etc.
I am trying to create a single loop by moving the start position and end position after creating the squares but I am stuck again. Wall

Any help would be appreciated again.
Thanks a lot for reading through.
Reply
#4
Made some progress with looping through the rows and creating 3x3 lists.

rowstartposition = 0
rowendposition = 3

for k in range(3):
    startposition = 0
    endposition = 3

    for j in range(3):
        squaresList=[]

        for i in range(startposition,endposition):
            squaresRow = (rows[i][rowstartposition:rowendposition])
            squaresList.extend(squaresRow)
        squares.append(squaresList)
        startposition += 3
        endposition +=3
        
    rowstartposition += 3
    rowendposition += 3
For the entire module, trying to check if the entered values make a valid SUDOKU or not -
One question though - my columns which were achieved through a transpose using 'zip' contains a list with tuples inside whereas my rows and squares contain lists within lists.
Is there a way to make the columns also follow the same structure?
Or does it only create tuples when we use 'zip' to transpose values?
Huh


If there is a cleaner approach, I am all ears as I have been coding in PY just for the last month.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help please. Looping the same SQL query over different databases and combine them danlin123 3 2,094 Sep-23-2020, 02:31 PM
Last Post: danlin123
  Dictionaries in Lists szbeco 6 2,726 Nov-07-2019, 10:16 AM
Last Post: szbeco
  Help with Dictionaries and Lists of Lists Nate5800 5 77,461 Apr-23-2018, 06:42 PM
Last Post: Nate5800
  Trouble displaying items from lists Liquid_Ocelot 8 6,469 May-18-2017, 01:37 PM
Last Post: Ofnuts
  Creating lists or arrays as the input nickalvar 4 4,201 May-03-2017, 04:46 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020