Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is there a way to make an array of words in python?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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)


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading