Answering in case you haven't made any headway on it.
First you need to create your shelf button using the cmds.shelfButton command. It's up to you to work out the styling on that, but ensure you use the parent flag to select the proper shelf. See below.
cmds.shelfButton(parent=d[1])
Then you can use the position flag to reposition shelf buttons within your shelf using cmds.shelfLayout. The position flag requires a string and an int. The string is the child by name that you would like to move (I've used string.format to achieve this), and secondly is the 1-based index of where you want to move the button to. Since the newly created shelf button is added as the last item of a shelf, I can easily select it with a -1 index.
cmds.shelfLayout(d[1], edit=True, position='{0}'.format(e[-1]), 2))
These are the 2 things you need to be on your way to figuring out how this all fits into your code. Hope this helps!