Dictionaries and F strings

I am studying a python course, and going back over the material. One of the examples uses a dictionary and a for loop. It uses a print statement to print out the dictionary contents and that works, however when I try to convert the print statement to an f string it fails. I have tried various combinations and I have also read through several guides on using f strings and dictionaries with no luck.

I would apreciate if anyone could tell me where I am going wrong and how I should rewrite this for loop to print out correctly:

#here is an example of a Dictionary sequence which prints both the key and value denoted as K for Key and V for value
print (‘here is a list value of key value pairs’)
x = { ‘one’: 1, ‘two’: 2, ‘three’: 3, ‘four’: 4, ‘five’: 5}

#I have commented out the working print statement below and tried to unsuccessfully replace it with an f’ string.

for k, v in x.items():
#print(‘Dictionary with key and value - k: {}, v: {}’.format(k, v))
print(f’This is a dictionary Key Pair value {k[“k”]} v{[“v”]}’)

Which version of Python are you using, and what results do you get when you try the modified code?

Wait… your code is not correct :slight_smile:

k and v are already directly-usable values, you don’t need to use them as keys or indices.

print(f'This is a dictionary Key Pair value {k} {v}')

If you want them labeled like the original code:

print(f'This is a dictionary Key Pair value k: {k}, v: {v}')

Look at the expressions inside the {}format markers:


Do they look like what you would write outside a format string? I
suspect you just want


and therefore a format string:

print(f'This is a dictionary Key Pair value k: {k}, v: {v}')

or with a current Python:

print(f'This is a dictionary Key Pair value {k=}, {v=}')

I suspect you’re overcomplicating things in your mind.

Cameron Simpson cs@cskk.id.au

Hi All, thanks for this, sorry for my late reply!! I am not getting any notifications to responses. Above code worked thanks all!