Search python data dictionary

Asked

Viewed 79 times

0

I need to scroll through a Python data dictionary, taking the values and counting the positions from start to end of each value sequentially, then turning it into an example tuple:

dict = {'dado1': 'teste01', 'dado2': 'teste002', 'dado3': 'teste0004050'}

dado1 -> value: teste01 - has 7 characters ranging from 0 to 7

dado2 -> value: teste002 - has 8 characters ranging from 8 to 15

dado3 -> value: teste0004050 - has 12 characters ranging from 16 to 27

tupla = [(0,7),(8,15),(16,27)]
  • 3

    Could you tell me what the criterion is? If you have 7 characters and their indexing in the array starts at 0, then it should go to 6, no?

3 answers

1

In python you can traverse through an iterable using some tools:

  • Iteration
  • List comprehension
  • Map
  • Recursiveness

Iteration is the repetition of a process aiming to generate a result.

In computing, iteration is the marking technique of a block of instructions in a computer program by a defined number of repetitions. This instruction block is considered iterative ; a computer scientist can also refer to this block of instructions as an "iteration".

The pseudocode below is an example of iteration:

for item in coleção:
 faça algo com o item

source: wikpedia

The statement for python iterates over the items of a sequence to instead of specifying numerical values or conditions. It’s more like the declaration foreach found in other lingagen

Applying iteration to the proposed dictionary in the question:

f=0
l=[]

for s in dict.values():
  l.append((f, (f:= f + len(s)) - 1))

print(l)                               #[(0, 6), (7, 14), (15, 26)]

List comprehension is a syntactic construct available in some programming languages to create a list based on existing lists

List comprehension or list abstractions are syntactic structures describing how existing lists or other eternal objects are processed to create new lists from them.

They are written in some programming languages like B, Python Haskell or Common Lisp supported and in analogy with the notation descriptive of sets.
source: wikpedia

List comprehension provides a more compact syntax when you want to create a new list based on the values of an existing list.

Applying list comprehension to the dictionary proposed in the question:

f=0
print([(f, (f:= f + len(s)) - 1) for s in dict.values()])   #[(0, 6), (7, 14), (15, 26)]

Map is a function that applies a certain function to an eternal.

In many programming languages, map an order function in which a given function is applied to each element of a functor , for example, in a list , the result is a list equally long results.

Below is an example to add 1 to each number in a list:

inserir a descrição da imagem aqui source:wikpedia

The function map() returns an iterator that applies a script for each item of an iterable.

Applying map to the proposed dictionary in the question:

def ccontador():
  f = 0                                  
  def contador(s):
    nonlocal f                            
    return (f, (f:= f + len(s)) - 1)
  return contador

cont = ccontador()

print([*map(cont, dict.values())])       #[(0, 6), (7, 14), (15, 26)]

Recursiveness means that when describing something, a reference to the description itself appears in the description.

In computer science, recursion is the definition of a subroutine (function or method) that can invoke itself. An example of recursive application can be found in the parsers recursive syntactics for programming languages. The large advantage of recursion is in the possibility of using a finite computer to define, analyze or produce a stock potentially infinite sentences, designs or other data.
source: wikpedia

Applying recursiveness to the proposed dictionary in the question:

def rcontador(v, f=0):
  if len(v) == 0:
    return [] 
  s = v[0]
  return [(f, (f:= f + len(s)) - 1)].extend((rcontador(v[1:-1]),f))

print(rcontador([*dict.values()]))          #[(0, 6), (7, 14), (15, 26)]

0

first let’s go through the dictionary with a for

dict = {'dado1': 'teste01', 'dado2': 'teste002', 'dado3': 'teste0004050'}
tupla = []

for key in dict:
    pass

Next we will add the len of the `string, summed with the previous value

dict = {'dado1': 'teste01', 'dado2': 'teste002', 'dado3': 'teste0004050'}
tupla = []
valAnterior = 0

for key in dict:
    tupla.append((valAnterior, valAnterior+len(dict[key])))
    valAnterior += len(dict[key])+1

print(tupla)

0


First let’s go through the dictionary with a for. At the same time we iterate in the loop we already mount the array output tupla, that we add the size of string, added to the previous value, these values are stored temporarily in the variable tmp.

dict = {'dado1': 'teste01', 'dado2': 'teste002', 'dado3': 'teste0004050'}
tupla = []
inicio = 0
fim = 0
tmp = 0
for elem in dict:
    print(dict[elem])
    inicio = tmp
    fim = inicio + len(dict[elem])-1
    tmp = fim + 1
    tupla.append((inicio,fim))
print(tupla)

Browser other questions tagged

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