0

Looking for extra enlightenment on *args and **kwargs, I came across the following short piece of code:

def concatenate(**kwargs):
    result = ""
    # Iterating over the Python kwargs dictionary
    for arg in kwargs.values():
        result += arg
    return result

print(concatenate(a="Real", b="Python", c="Is", d="Great", e="!"))

The page says it would produce:

RealPythonIsGreat!

And it indeed does. With Python 3.7.2. But that is what it spits when I run it with Python 2.7.16:

RealIsPython!Great

It shuffles the terms in a totally nonsensical, Yoda-like way. Why?

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 3
    `kwargs` is a dictionary, and dictionaries didn't have a specific order until more recent Python versions. – mkrieger1 Dec 20 '19 at 13:34
  • 2
    And that is why we have `PEP 468` https://www.python.org/dev/peps/pep-0468/ – Raj Dec 20 '19 at 13:35
  • 1
    Python 2 isn't a thing anymore, don't even bother with it: https://pythonclock.org/ – cglacet Dec 20 '19 at 13:36
  • 1
    Does this answer your question? [Using an OrderedDict in \*\*kwargs](https://stackoverflow.com/questions/26748097/using-an-ordereddict-in-kwargs) – Raj Dec 20 '19 at 13:36
  • But I don't see why you would use keyword args if you don't care about their names, just use a list. – cglacet Dec 20 '19 at 13:37

1 Answers1

1

A dictionary is a collection which is unordered. At least for older Python versions. Only Python 3.6 onwards keeps the insertion order.

Burkhard
  • 14,596
  • 22
  • 87
  • 108
  • Yes, but it is also "orderly unordered", that is, I (obviously) always get the same result no matter how many times I execute the script. Why is that "unordered order" preferred to any other? If I remove the `.values()` I get "acbed", which is also nonsense. – Fausto Arinos Barbuto Dec 20 '19 at 15:21