The obvious solution is to just use iterkeys
and itervalues
instead of iteritems
:
key_string = ','.join(d.iterkeys())
val_string = ','.join(d.itervalues())
If you're worried about the keys and values showing up in different orders, while Python allows dicts to iterate in any order they want, it does document here that if you iterate them over and over without doing anything else between you will get the same order:
If items()
, keys()
, values()
, iteritems()
, iterkeys()
, and itervalues()
are called with no intervening modifications to the dictionary, the lists will directly correspond.
(The 2.7 docs were never updated to say so, but it's also true for viewitems
, viewkeys
, and viewvalues
.)
At least in CPython, it will probably be slightly more efficient to use keys
and values
instead of iterkeys
and itervalues
(because, when given an iterator, the CPython implementation of str.join
just makes a list out of it), but I doubt that matters. As Padraic Cunningham points out in the comments, for the keys (but not the values), you may be able to get the same list even faster with just list(d)
instead of d.keys()
(although maybe not—it avoids a LOAD_ATTR
call, but at the cost of a LOAD_NAME
, unless you've first copied list
to a local so it can be LOAD_FAST
ed).
Finally, if you want to do it with iteritems
(let's say you're using a broken not-quite-compliant Python interpreter that randomizes the iteration order each time), you can use zip
for that:
keys, values = zip(*d.iteritems())
That turns a sequence of pairs into a pair of sequences.