I have a python 2.7 script that is generating Verilog code. I need to create a comma-separated list of the keys in a dictionary. For example, if the keys in the dictionary are 'A', 'B', and 'C', I need to be able to print to the generated file 'A, B, C', or 'B, A, C', or whatever order the keys come out (I don't care about the order). The interesting part is that I can't have a comma at the end, so I need to identify either the first item that is being returned or the last in order to handle one of them differently.
Is there a clean, 'Pythonic' way to identify the first or last item being returned by iteritems?
Unlike Looping over a dictionary without first and last element, I do want all of the items and I don't care about the returned order. Using the method in the answers to that question to convert the dictionary to a list, then explicitly iterating through the items and handling the first or last items differently seems like a lot of contortion.
The work-around I am currently using feels very 'C-ish': I set a 'first_item' variable to True before the iteritems, then test for it inside the loop, do something different for the first item and then change it to False. This works, but isn't a particularly elegant solution:
# Generate the group enum declaration
fp.write('enum {')
first_item = True
for k,v in c.iteritems():
if first_item:
first_item = False
fp.write(k)
else:
fp.write(', ' + k)
fp.write('} group;\n')
And the only hack I could come up for differentiating the last item is even uglier - set a variable to len(dictionary), then decrement it each pass of the iteritems loop and do something different when it gets to 1.
Uglier still, IMO, is adding the ', ' + k
to a string a for every key, then removing the first two characters.
Any suggestions for how to do this more cleanly than the work-around shown above?