1

I'm trying to learn string formatting in Python and I was wondering if you can do something like this:

print(f'{element[i].key}: {element[i]}\n{element[i].key}:{element[i]}\' for i in range(2))

Basically, I want to run a for loop within a print so I can iterate and print different values within a dictionary. I feel like I have seen something like this before but I have no idea what the name of it is or how to do it.

0

3 Answers 3

5

I think this is what you're after:

my_dict = {'a': 'b', 'c': 'd'}
print('\n'.join(f'{key}: {value}' for key, value in my_dict.items()))

But remember that putting everything on a single line isn't a goal in itself. It's OK to aim for efficiency or performance, but readability and clarity are sometimes even more important.

Sign up to request clarification or add additional context in comments.

Comments

4

A basic list comprehension with f-string will do the job:

    [print(f'{key}:{value}') for key, value in my_dict.items()]

1 Comment

Note that this has the overhead of calling print repeatedly. This also means that it doesn't work in cases where there is no linefeed required after each value printed. It's basically (ab)using the list comprehension to put a regular for loop on a single line. Very clear and easy to read though, but so would a 2-line for .. print be.
1

Instead of running a for loop within a print, you should put a print inside of a for loop.

For example:

for i in range(2):
    print(f'{element[i].key}: {element[i]}\n{element[i].key}:{element[i]}\')

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.