1

The general idea is to make an OrderedDict first and pass this to the function, however this looks messy. There's a lot of suggestions on making **kwargs ordered, but this seems to be the only solution - In Python, what determines the order while iterating through kwargs?

However, I'm wondering is it possible to use a few python features to allow a simple input? So myFunction( a=5, c=2, b=3 ) will keep the order, without having to wrap the inside values in an OrderedDict.

Here's some code which won't work but it's the idea I have and don't know how to implement

class testing:
    def __init__( self, kwargs ):
        print kwargs

testing2 = testing( OrderedDict( valueToInput ) )

testing2( a=5, c=2, b=3 )

Would it be possible at all? If there is such a way to do what I did with the testing2 value, that'd be really useful for other purposes too.

Community
  • 1
  • 1
Peter
  • 3,186
  • 3
  • 26
  • 59
  • 3
    Why are you using keyword arguments *at all* if order is important? You could also just process keyword arguments in a fixed order you picked up-front, but what is the real problem you are trying to solve here? – Martijn Pieters Nov 21 '14 at 17:18
  • 2
    I've done Python for a few years and never needed/wanted ordered kwargs. Isn't the point of `**kwargs` that you recognise them by the key. If you want to parse by the order just take `*args` instead and you have a list. – Anentropic Nov 21 '14 at 17:19
  • if you want to print out the `kwargs` in a pretty form or something then you could perhaps take `**kwargs` as usual, take its `.keys()` list and sort that in some way, then iterate over your sorted keys getting values from the kwargs... – Anentropic Nov 21 '14 at 17:23
  • ...actually this is pretty much what @MartijnPieters already suggested in the first comment :) – Anentropic Nov 21 '14 at 17:24
  • I tried that, but I'd like it to somehow stay in the order it's input, which might not necessarily be alphabetical. I need the two values for each part (value=input) so as far as I know I can't use the `*args` method, I'll experiment a bit more with this though – Peter Nov 21 '14 at 18:48
  • Martijn, how would I process them in a fixed order by the way? And I tried *args, but can't seem to get it working without enclosing everything within a string, which kinda defeats the objective of trying to keep the input very simple. If there is any way to transfer these values to a function in order to then turn to a string, that would be fine, I just need to get them passed in the format `function(a=1, b=2, c=3)` if possible – Peter Nov 21 '14 at 18:51

1 Answers1

1

This has (finally) been solved with python 3.6 as dict got ordered.

See: PEP468 and what's new. Therefore making

magu_
  • 4,766
  • 3
  • 45
  • 79