1

I wrote a simple function to retrieve three outputs from a string. When I want to use the returned value in other functions the order changes. For example:

def parsetrack2(trackstr):

    cardnumber, date = trackstr.split('=')
    expiryyear = date[0:2]
    expirymonth = date[2:4]

    return{cardnumber,expiryyear,expirymonth}

When I want to pass the cardnumber and expiryyear to another function, sometimes order changes and other times it is right? Why is that?

How should I change it to prevent that variation?

PaulG
  • 13,871
  • 9
  • 56
  • 78
Likak
  • 373
  • 1
  • 5
  • 19

2 Answers2

2

That happens because you are returning a dictionaire instead of a list / tuple. (dicts do not save the order of the elements, while lists / tuples does)

Just change the :

return{cardnumber,epxiryyear,epxirymonth} 

to:

return(cardnumber,epxiryyear,epxirymonth)

Then the result order will remain the same.

Adriano Martins
  • 1,788
  • 1
  • 19
  • 23
  • 5
    Actually, you are returning a set, which also does not have order. – zemekeneng Dec 14 '16 at 01:33
  • 2
    It's not a `dict`, it's a `set`. Also, typically, when returning multiple values, I typically don't bother with parens at all; I use parens when I'm making a data structure, but in this case, the fact that Python implements multiple return values as a `tuple` is irrelevant (the caller should be unpacking them anyway), so I'd just go with `return cardnumber, epxiryyear, epxirymonth` – ShadowRanger Dec 14 '16 at 01:34
2

This:

{item_1, item_2, ...}

is actually a set literal (not a dict). A set is an unordered collection of items with no repeats. Therefore, the order of the items returned is random. Instead do this

def func():
    return 1, 2, 3

>>> a, b, c = func()
>>> a
1
>>> b
2
>>> c
3
Adam Van Prooyen
  • 891
  • 7
  • 17