Creation of python Dict

Asked

Viewed 1,167 times

1

Time, has a class that creates dicts and stores them in a list slot:

class Pagina:

def __init__(self, keys, palavras, tamanhoP):
    aux = list(zip(keys, palavras))
    self.paginas = list()

    for i in range(0, len(aux), tamanhoP):
        self.paginas.append(dict(aux[i:i + tamanhoP]))

def __getitem__(self, num):
    return f'Página {num}: {self.paginas[num]}'

def __repr__(self):
    return f'Todas as páginas: {self.paginas}'

def get_key_pagina(self, num):
    for i in range(0, len(self.paginas)):
        if num in self.paginas[i]:
            return f'Palavra na Página: {i}'

But now I need to create a new Dict in receiving the same Keys and the position in Dict of the above class, it is possible ?

Follow my attempt so far:

    def novoDict(self, keys):
    aux = list()
    for ii in keys:
        for i in range(0, len(self.paginas)):
            if ii in self.paginas[i]:
                aux.append(dict(aux[ii: i]))
    return f'{aux[0]}'

But the following error returns to me:

dictionary update sequence element #0 has length 0; 2 is required

What would the new Dict look like, ex:

{key 0: Página 0}

Test example:

listaP = ['x', 'y', 'z', 'w']
listaI = [1, 2, 3, 4]

Instantiating the object:

x = Pagina(listaI, listaP, 2)

Exit:

Página 0: {1: 'x', 2: 'y'}
Página 1: {3: 'z', 4: 'w'}

What I want to get:

{'x': 0, 'y': 0, 'z': 1, 'w': 1}
  • 1

    I couldn’t understand what you wanted to do but zip() shall be applied on a rolling basis and in their case ii is an element of keys which must be of the numpy.int32 and i is the type int.

  • So friend, I want to create a Dict like this: {key 0 : Key position in the list "pages"}, I saw the zip error, I tried to modify to the following: (I edited in the question), but now the program takes a long time to give me an answer to the function.

  • Someone can help?

  • It would not be the case to replace all this functionnovoDict(self, keys) by that line of code list(zip(keys,self.paginas)) ? I made a simplified example of what I understood of your problem https://repl.it/repls/BriskFaintFormats see if I interpreted it correctly?

  • Senho Augusto, at first I have a list of Dict like this: {key: word}, where depending on the page size (information given by the user), I divide this list into slices and store in sub-lists (pages). From this I want to create a new dictionary only with the key and its position in the new list (i.e., on the page), e.g.: {key: page 0}

  • 1

    A practical example for testing is missing. It would be nice to have data samples and an example showing the methods being applied to these data.

  • I added a test example, if you can take a look

Show 3 more comments

1 answer

2


I didn’t understand what the parameter would be for keys, because it seems to me that you want to generate a new dictionary with all pages. So it would look like this:

def novo_dict(self):
    d = {}
    for i, pag in enumerate(self.paginas):
        for v in pag.values():
            d[v] = i
    return d

I use enumerate to scroll through pages at the same time as I get their index. That is, at each iteration, the variable pag will be the dictionary representing one of the pages, and the i is its index.

Then I go through the values of each page and add them in the new dictionary, associating them to the page number (in this case, i).

Using your example:

listaP = ['x', 'y', 'z', 'w']
listaI = [1, 2, 3, 4]

x = Pagina(listaI, listaP, 2)
print(x.novo_dict())

Exit:

{'x': 0, 'y': 0, 'z': 1, 'w': 1}
  • opa, the goal was the same, but is returning me an error: d[v] = i Typeerror: unhashable type: 'numpy.ndarray'

  • Where am I going wrong ?

  • @placeholder.The question code has no numpy array. Anyway, if your code has this, I suggest you review your goal when creating this dictionary, because arrays, lists and any mutable object should not be used as keys to a dictionary, as recommended by documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.