Skip to content
Advertisement

How to iterate dict in string.format

I read a lot of tutorials, but can not find how to iterate dict in string.format like this:

JavaScript

which I want a result like this:

JavaScript

so I can print variable length dict.

JavaScript

Then I got error.

Advertisement

Answer

Currently your output is:

JavaScript

That’s because k for k,v in dict is a generator expression. Don’t confuse it with set comprehension, those curly braces are for f-string.

But of course that k for k,v in dict is problematic. When you iterate over a dictionary itself, it gives you keys. So for the first iteration "this" comes back. you can’t unpack "this" into two variables. k, v = "this".

You can use this:

JavaScript

output:

JavaScript

This join works because keys and values are strings in your dictionary. If they are not, you should convert them like:

JavaScript

For the first one you could also use print(f'the key is {" ".join(d)}') as dictionaries will give keys in the iteration by default.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement