# Se trata de una función donde con una lista de cadenas has de transformar las
#cadenas pares en claves y las impares en valores en un diccionario.
def toDictionary(s):
result = {}
k = ""
v = ""
i = 0
if len(s) == 0:
return {}
else:
for c in s:
if i % 2 == 0:
k = c
else:
v = c
result[k] = v
i += 1
return result
The code is correct and does what is expected of it if the list has an even number of elements.
If the number of elements is odd, it does something reasonable, which is that it considers only the first N-1 elements (discarding the "excess" at the end). However, it may not meet the specification for the latter case, but there is nothing in your statement that prohibits this behavior.
However, although it works, the style can be improved.
For example, you can remove the first
else:
one since if the list is empty it will do areturn
and exit the function, and if it is not empty it will continue doing the rest of the function, which can therefore go outside of theelse
, reducing the indentation needed in the code:This is not purely aesthetic, it also makes it easier to read by reducing its cyclomatic complexity.
What's more, the
if
complete one is left over, since if the list is empty it won't ever iterate infor
, and therefore it will return what was inresultado
, which was already an empty list. It also supersedes the initialization of the variablesk
andv
. It doesn't matter what initial value they have because in the loop you will change that value to them anyway. So:Finally, to avoid initializing and incrementing
i
, you can make use of the python functionenumerate()
. You pass this function a list and it returns an iterator that you can dofor
. Every time you iterate you will get two pieces of data: the first will be an integer which is the index of the element. The second will be the value of the element. Using this trick:The code has gained in readability and simplicity, but from a functional point of view it is equivalent to yours, and will produce the same results, so it will probably still be invalid. Until the specification of the problem and an example of a case in which it fails is not clearer, we cannot help you further.
Edition
One last trick (but functionally still equivalent). If you use you
s[::2]
can get the even elements of the list, and if you uses[1::2]
the odd elements, then the slice operator admits a third value for the "step" between elements. If you combine both results withzip()
, you can get key and value pairs:I don't think we'll gain much readability by doing it this way, but I thought you might be interested in learning about this trick for other occasions.
And for that matter, if we get carried away by the "leave it on a line" fever (it's a contagious fever and not always desirable...) you can use the dict comprehension syntax :
It still gives the same results as your original function.