What is an elegant way to convert a python dictionary into a comma separated keys string and a comma separated values string?

28,796

Solution 1

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_FASTed).


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.

Solution 2

You could do it like this:

key_string = ','.join(dict.keys()) 
val_string = ','.join(dict.values())

Solution 3

Using the same function str.join(iterable), if dictionary values are not all strings then using list-comprehension shorthand:

d = {'a': '1', 'b': 2, 'c': {'d': 3}, 'e': [4,5,6]}
print(",".join(d.keys()))
print(",".join([str(e) for e in d.values()]))

Output:

a,b,c,e
1,2,{'d': 3},[4, 5, 6]

If you want custom formatting then this makes for an elegant abstraction. Replace str(e) with your custom formatter myFormatter(e).

Share:
28,796
nimeshkiranverma
Author by

nimeshkiranverma

Entrepreneur Passionate Programmer Open Source Enthusiast Ex Linkedin Employee Artist IIT Delhi Alumnus Studied Maths and Computing for 5 years Love to collaborate and provide a helping hand Presently pursuing a Fin-Tech venture Linkedin: https://www.linkedin.com/in/nimeshkverma/ Gmail: [email protected]

Updated on July 17, 2022

Comments

  • nimeshkiranverma
    nimeshkiranverma almost 2 years

    I have a dictionary as follows:-

    dict={'a':'1','b':'2', 'c':'3'}
    

    To convert it into into a comma separated keys string key_string and a comma separated values string val_string I do the following:-

    key_list=[]
    val_list=[]
    
     for key,value in dict.iteritems():
         key_list.append(key)
         val_list.append(value)
    
     key_string = ','.join(key_list)
     val_string = ','.join(val_list)
    

    The result is

     key_string = "a,b,c"
     val_string = "1,2,3" 
    

    Is there a more efficient/elegant way to do this?