0

I am new to learning python and a bit confused and hoping i can get some help.

I have a dict here

my_dict = { "abc":1, "bvc":2, "mnb":3}

I am getting the keys using :-

keys = my_dict.keys()
for key in keys:
print(key)

and i get the output:-

"abc"
"bvc"
"mnb"

How can i get the output in the same line like this?

"abc", "bvc", "mnb"

I tried using

print(key.join(' ')+',')

in my loop but it doesn't work as expected.

Any help will be appreciated.

2
  • list(my_dict.keys()) ? Commented Apr 29, 2021 at 18:11
  • 2
    Use print(key,end=", "). Commented Apr 29, 2021 at 18:12

4 Answers 4

1

To avoid printing a new line every time you can use print(key, end="") or also print(key, end=", ") and can then make so that it does not write the last comma.

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

Comments

0

Using

print(*my_dict.keys())

will unpack the keys into an argument list for print and product output

abc bvc mnb

If you need commas in the output, you can add the sep=", " keyword:

print(*my_dict.keys(),sep=", ")

Comments

0

You can a make a string.join

print(', '.join(my_dict.keys()))

Comments

0

By default print() method add the new line character , if we want to override this then we need pass the explicitly char..

print(key,end=", ")

Comments