Saturday, June 15, 2019

Convert a python dictionary to comma separated key list and comma separated value list

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" 

No comments:

Post a Comment