Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: dictionary to string, custom format?

currently I'm displaying keys only, each in new line:

'<br/>'.join(mydict) 

how do I display them like key:: value, each in the new line?

like image 607
migajek Avatar asked Dec 15 '11 11:12

migajek


2 Answers

Go through the dict.items() iterator that will yield a key, value tuple:

'<br/>'.join(['%s:: %s' % (key, value) for (key, value) in d.items()]) 

Updated with modern f-string notation:

'<br/>'.join([f'{key}:: {value}' for key, value in d.items()]) 
like image 84
Filip Dupanović Avatar answered Sep 27 '22 19:09

Filip Dupanović


That, or an even cooler solution using join to join both items and the (key,value) pairs, avoiding the now-obsolete % interpolation, using only a single dummy variable _, and dropping the redundant list comprehension:

"<br/>".join(":: ".join(_) for _ in mydict.items()) 

Be aware that dicts have no ordering, so without sorted() you might not get what you want:

>>> mydict = dict(a="A", b="B", c="C") >>> ", ".join("=".join(_) for _ in mydict.items()) 'a=A, c=C, b=B' 

This also only work when all keys and values are strings, otherwise join will complain. A more robust solution would be:

", ".join("=".join((str(k),str(v))) for k,v in mydict.items()) 

Now it works great, even for keys and values of mixed types:

>>> mydict = {'1':1, 2:'2', 3:3} >>> ", ".join("=".join((str(k),str(v))) for k,v in mydict.items()) '2=2, 3=3, 1=1' 

Of course, for mixed types a plain sorted() will not work as expected. Use it only if you know all keys are strings (or all numeric, etc). In the former case, you can drop the first str() too:

>>> mydict = dict(a=1, b=2, c=2) >>> ", ".join("=".join((k,str(v))) for k,v in sorted(mydict.items())) 'a=1, b=2, c=3' 
like image 26
MestreLion Avatar answered Sep 27 '22 21:09

MestreLion