Home > Software design >  is there a way to make an array of words in python?
is there a way to make an array of words in python?

Time:01-31

i am a beginner in python my wish is to make an array of n lines and n rows. I have a dictionnary of words and i need to put them in an array n*n . provisions ={'cake':'20','eggs':'10','tomatoes':'4','potatoes':'2','bread':'4'}

| /  | 1           | 2            |
| 1  | cake        | eggs         |
| 2  | tomatoes    | potatoes     |

that is an example of what i want. we have here an array of 2 lines and 2 rows. i can have a dictionnary of more than 5 elements.That is just for an example.

import string

provisions = {'cake':'20','eggs':'10','tomatoes':'4','potatoes':'2','bread':'3'} 
tab = []

#i can modify the n for having an array of n*n no matter if provisions has more elements

n = 2
j = 0
i = 0

if provisions:
    for k,v in provisions.items():
        while i<n:
            while j<n:
                print(f"{k}")
                tab[[i],[j]] = provisions[i]
                j  = 1
            i  = 1

CodePudding user response:

 You can try the code below.Iterate the dict, count current index (m variable)and compute position in the matrix.

import math

provisions = {'cake': '20', 'eggs': '10', 'tomatoes': '4', 'potatoes': '2', 'bread': '3'}

n = 2
# init matrix
tab = [[0 for x in range(n)] for y in range(n)]

# I can modify the n for having an array of n*n no
# matter if provisions has more elements

# index in the dict
m = 0
if provisions:
    for k, v in provisions.items():
        # prevent index overflow
        if m < n * n:
            # compute position in matrix
            tab[math.floor(m / n)][m % n] = k
            m = m   1

print(tab)



 If you want to determine element for position tab[i][j],you first get the index of this element : i * n j(the first element in the dict is 0).Unfortunately, there is still no dedicated method to index into keys() / values() of the dictionary, you can find something in this answer.

  • Related