def square100():
d = {f"{x}" : f"{x**2}" for x in range(101)}
print(d)
if __name__ == "__main__":
quadrado100()
this function return the values in ascending order.
def square100():
d = {f"{x} : {x**2}" for x in range(101)}
print(d)
if __name__ == "__main__":
quadrado100()
but this function that should do the same thing, shows in a random order. does anyone know why?
nothing to say here
CodePudding user response:
The latter is a set comprehension, not a dict comprehension (neither one is a list comprehension); the difference is that there is no : (at top level, outside string quotes and the like) separating a key from a value in a set literal or comprehension, while there is one in a dict literal or comprehension.
sets have arbitrary order (effectively random for strings; it will change between different runs of Python, and can change even within a single run of Python based on the order in which items are added and removed), while dicts (in 3.6 as an implementation detail, and in 3.7 as a language guarantee) are insertion-ordered. So your first bit of a code (a dict comprehension) retains order, while the latter, based on sets, does not.
