Doubt about dictionaries in Python

1

What is the purpose of p in the dictionary?

p = Clase()
for c in diccionario.keys():
  if variable == c:
    diccionario[c](p)
    
asked by federico 27.12.2017 в 22:28
source

1 answer

1

The parentheses of (p) indicate a call to some "callable" type (such as a function, method, class ...) or to a class instance that has the __call__ method defined . At the same time it is called, it is passed instance p as argument . Therefore the dictionary must have as values something that can be called and that accepts at least one argument.

To know exactly what your code does, you need more context, such as the content of diccionario , the definition of Clase , etc. But we can create a reproducible example to explain the idea:

class Clase:
    pass

# Función que recibe un argumento y lo imprime:
def foo(arg):
    print("Función foo ha sido llamada con argumento {}.".format(arg))

# Clase con instancias callables:
class Bar:
    def __call__(self, arg):
        print("Instancia de Bar ha sido llamada con argumento {}.".format(arg))

diccionario = {"a": print,  "b": foo,  "c": Bar()}
p = Clase()

variable = "a"
for c in diccionario.keys():
    if variable == c:
        diccionario[variable](p)

variable = "b"
for c in diccionario.keys():
    if variable == c:
        diccionario[c](p)

variable = "c"
for c in diccionario.keys():
    if variable == c:
        diccionario[c](p)

Exit:

  

< __ main __. Object class at 0x7f0bcfbf23c8 >   Function foo has been called with argument < __ main __. Class object at 0x7f0bcfbf23c8 & gt ;.
  Instance of Bar has been called with argument < __ main __. Class object at 0x7f0bcfbf23c8 & gt ;.

See how the key "a" of the dictionary has the function "built-in" · print (Python 3), the key "b" our function foo and the key "c" an instance of Bar .

As you see diccionario[c](p) you simply get the value associated with the key c and call it passing it as an argument p :

  • diccionario["a"](p) is the same as print(p)

  • diccionario["b"](p) is the same as foo(p)

  • diccionario["c"](p) is the same as Bar()(p)

To all this, the for is meaningless in this case . The keys of a dictionary are unique, since there is only one key (if any) equal to the value of variable , instead of iterating over them, a simple, simpler and more efficient conditional is enough:

if variable in diccionario:
    diccionario[variable](p)

Returning to your specific question, p has no purpose in relation to the dictionary beyond being the argument to move to its "callable" values when they are called.

    
answered by 27.12.2017 / 23:58
source