46

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?

5 Answers 5

112

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()])
1
  • 3
    Less verbose if you don't unpack the tuple: '<br/>'.join(['%s:: %s' % kv for kv in d.items()])
    – Greg Bray
    Dec 29, 2018 at 2:15
11

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'
4
  • The last one is same data format of my dictionary. But when I try you solution It returns this message : TypeError: 'str' object is not callable
    – Jihye Seo
    Apr 21, 2021 at 7:57
  • @JihyeSeo: which one of my solutions are you trying, and what is your dict layout? I gave 3 alternatives: the simplest one requires both keys and values to be strings; the more robust one works with mixed data but can't be sorted(), and the last one expects uniform data (and string keys). It all depends on your data format.
    – MestreLion
    Apr 21, 2021 at 8:11
  • @JihyeSeo: Given your error, quite possibly you named a variable str, shadowing the builtin str class. Don't use builtin names to name your objects!
    – MestreLion
    Apr 21, 2021 at 8:22
  • The last one I used. I didn't use builtin str class. Anyway I solved it using different solution. Thanks a lot!
    – Jihye Seo
    Apr 21, 2021 at 8:32
7

In python 3.6 I prefer this syntax, which makes the code even more readable:

'<br/>'.join([f'{key}: {value}' for key, value in d.items()])

See PEP 498 -- Literal String Interpolation

3

If you wanted to be more pythonic, we can remove the for-comprehension altogether.

'<br/>'.join(map(':: '.join, mydict.items()))
1
  • 1
    just 1 ) is missing in the end: '<br/>'.join(map(':: '.join, mydict.items()))
    – L F
    Aug 2, 2021 at 17:41
1

I liked what Filip Dupanović did above. I modified this to be python3-ish using str.format method.

'<br/>'.join(['{0}:: {1}'.format(key, value) for (key, value) in d.items()])

I modified the above to generate a string I could feed to a SQL table create statement.

fieldpairs = ','.join(['{0} {1}'.format(key, value) for (key, value) in HiveTypes.items()])
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.