python - How to return a str containing key and value in a dictionary -


def dict_to_str(d):     """ (dict) -> str      return str containing each key , value in d. keys , values     separated space. each key-value pair separated comma.      >>> dict_to_str({3: 4, 5: 6})     '3 4,5 6'     """ 

how write body of function?

so far, have following:

for values in d.values():     print(values) items in dict.keys(d):     print(items) 

but don't know how make comes in right format. wanting make each value/item list, can coordinate example, value[0] , item[0], value[1] , item[1] , on

use str.join() , list comprehension:

','.join([' '.join(map(str, item)) item in d.iteritems()]) 

on python 3, replace .iteritems() .items(). map() used make sure both keys , values strings before joining.

demo:

>>> d = {3: 4, 5: 6} >>> ','.join([' '.join(map(str, item)) item in d.iteritems()]) '3 4,5 6' 

note order arbitrary; dictionaries not have set ordering (instead order depends on insertion , deletion history of keys).

wrapping in function left exercise reader.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -