Dictionary from list index

Asked

Viewed 245 times

-1

I have a list of names = [name1, name2, name3, etc]

Each name is to have associated information such as address, phone, etc.

I want to make a menu from the list index: print...

1 - Nome1

2 - Nome2

3 - Nome3

input("Enter your option:")

The dictionary from the list index:

If the user type 1, print the data of the name1; if 2, given in Nome2; etc....

I want, if I include or delete a name from the list, the dictionary should link the new index to the name, regardless of whether the inclusion was from the beginning, middle or end of the list.

Ex.: list [Peter, John, Joseph] ->

Menu:

1 - Peter

2 - John

3 - Joseph

User type '2' -> print John data

If I delete John, dictionary links index 2 to the name that stood in John’s place:

User type '2' -> print José data

You can make a dictionary like this?

1 answer

1


If you want an automatic index update, as you are writing, you do not have the slightest need for a dictionary.

In the list the dynamic change of indexes happens naturally - if, if you will access elements in a list by its index, its performance is equal to that of a dictionary. (Not that performance makes a difference in data sets of this size in interactive applications - it would make a difference for thousands of data items and Mili-second times).

In short: use a list. Since lists work with index from zero, you should remember yes, to add a "1" when displaying an index on the screen, and "subtract 1" whenever you convert a typed index back to an index in the list. Depending on the sophistication you want, you can even create a class that inherits from the list, and makes that index difference automatically - and you can still take advantage and convert the string index to int, so you don’t need to convert internally.

class MinhaLista(list):
    def __getitem__(self, index):
         if isinstance(index, str):
              index = int(index.strip())
         if not isinstance(index, int):
              raise TypeError(f"ìndices do tipo f{index.__class__}  não são suportados")
         return super().__getitem__(index - 1)
    def __setitem__(self, index, value):
         if isinstance(index, str):
              index = int(index.strip())
         if not isinstance(index, int):
              raise TypeError(f"ìndices do tipo f{index.__class__}  não são suportados)
         return super().__setitem__(index - 1, value)

The extra "if" to check if the index is integer is that this code will not support the use of "slices" - that is, the notation with "list[0:5]" to take a part of the data in a list.

converting the list to dictionary

As I mentioned, it’s not necessary, but if you really want to turn a list into a dictionary, this can be done on a line with a Dict-comprehension - but this model won’t have the automatic index adjustment you want.

For this, you can use the function enumerate, that in a for returns the index of each element of the sequence, and still accepts an optional parameter of the count start number:

dados = {indice: valor for indice, valor in enumerate(lista_de_dados, 1)}

Dictionary of automatic adjustment of indexes

If it were really necessary to create a dictionary with automatic index adjustment, this would be possible - yes - but as in the first example, it requires a specialized class. In this class it would be necessary to recreate all methods that alter the dictionary: __setitem__, __delitem__, pop, clear, update, popitem, setdefault, and, in addition to calling super() to perform the operation, perform the indexing of the entire dictionary. The indexing would be a Custoza operation in terms of processing - with the same algorithmic complexity as removing an element from a list, but in real terms, much longer because it would be done in Python code rather than running straight in native code. In fact, the simplest would be, in each of these methods, to discard the whole dictionary, and to recreate the same automatically, from the values() from the previous dictionary.

You can create a developer to be used in the methods that need this behavior, and the code would not even be so big - but I won’t, because really in the "real world" is better to keep a list even for this case.

Browser other questions tagged

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