wvano97
wvano97

Reputation: 82

Loop within string formatting in Python

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.

Upvotes: 1

Views: 120

Answers (3)

John Greenfield
John Greenfield

Reputation: 143

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

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

Upvotes: 4

balexander1
balexander1

Reputation: 222

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]}\')

Upvotes: 1

Grismar
Grismar

Reputation: 31319

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.

Upvotes: 5

Related Questions