Transform object to Dict in python

Asked

Viewed 684 times

2

Good team, blz ? So, I started to study python now and wanted a help from you on the following question: I need a class that receives two distinct arrays (words and key) and relates all elements of the two arrays, such as a Dict. ex: Word: 'test' | Key: 1 and store these combinations in a searchable data structure, both by word and key.

class tupla:

    def __init__(self, key, palavra):
        self.key = key
        self.palavra = palavra

    def __str__(self):
        return f'Key: {self.key} | Palavra: {self.palavra} \n'

    def to_dict(self):
        return self.__dict__

2 answers

2


If you just need to create a dictionary, you can use the function zip Python to list your two lists - and you don’t need almost any code:

novo_dict = {key: palavra for key, palavra in zip(keys, palavras)}

If you really want a class, the least you need is to use the method __getitem__.

The example below is rather inefficient, but it would work:

class MapLists:

    def __init__(self, keys, palavras):
        self.keys = list(keys)
        self.palavras = list(palavras)
    def __len__(self):
        return len(self.keys)
    def __getitem__(self, key):
        index = self.keys.index(key)
        return self.palavras[index]
    def to_dict(self):
        return {key: palavra for key, palavra in zip(self.keys, self.palavras)}
    def __repr__(self):
        return f"MapLists<{self.to_dict()}>"

In this class the correlation from one list to another is done only at the point where an item is retrieved, as if it were a dictionary - then it searches the list of "keys", and returns the equivalent element in the list of "words". This structure allows you to continue changing lists, like lists, while using the object, but it’s much, much slower than a normal dictionary (it won’t make a difference to less than 1000 searches in less than 100 items). The method to_dict uses the example I gave earlier to create a new dictionary with the values.

  • Ball showw, that’s exactly what you need. Sorry for the layperson, but what about the "main" how do I pass the two arrays to the class "Maplist", display all created objects and one in specific, through the (key)? NOTE: Because I was able to do the whole project without using POO, but this teacher asked this way.

  • that there is not so "OOP" - beyond the OOP this code makes use of the special method __getitem__ which is filed by Python when you use your object as a dictionary or a list (with objeto[chave]). I did not understand the idea of "all created objects" - you can by all the "Maplists" you create in a list - there you get all of them visible. Or, within a `Maplists", the "to_dict" method returns a dictionary where you have all key/value pairs.

  • I think it is easier to exemplify: table = Maplists(listIndices, listPalavras) print(table.to_dict()) - The result I get is exactly what I wanted, but if I want to print the element with the key: 10, as I do ?

  • That: tabela[10]

  • It was as I had tried, but gives the following error: Traceback (Most recent call last): File "C:/Users/afons/Pycharmprojects/Machinelearning/main.py", line 26, in <module> print(table[67]) File "C: Users afons Pycharmprojects Machinelearning tupla.py", line 11, in getitem index = self.keys.index(key) Attributeerror: numpy.ndarray 'Object has no attribute 'index'

  • but -- a "ndarray" is not a "list"? Since the beginner usually uses the terms interchangeably, and had no example of what their data was, the code was made for lists. If they are one-dimensional arrays, you can turn them into lists in the __init__ - I’ll change the code for that

  • Damn, now it’s turned too flat. Obg even, you’re the guy ! haha

Show 2 more comments

1

No need to create a new class. Uses python’s built-in functions.

python already has a function to join lists. For example:

chave=['a','b','c']
valor=[1,2,3]

d = dict(zip(chave,valor))

Iput

d['a']

Output

1

Only with these commands can you 'zip' the key-value sets.

You can then use the keys to return the values.

  • Yes, I also believe I did not need to, I already knew the zip, but it is the teacher’s requirement to create a class for this, where each combination is an object. can help me ?

Browser other questions tagged

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