Home > Net >  Print a list inside a dictionary without brackets
Print a list inside a dictionary without brackets

Time:09-10

The following code:

a={"hello":[23,],90:["Hi",],25:[54,]}
for i in a:
    hrs=print(a[i],": ")

Has this output:

[23]:
["Hi"]:
[25]:

Whereas I need the output to be printed without the brackets like:

23:
"Hi":
25:

CodePudding user response:

Try this:

a={"hello":[23,],90:["Hi",],25:[54,]}
for i in a:
    print(repr(a[i][0]), ':', sep='')

Output:

23:
'Hi':
54:

CodePudding user response:

a = {"hello": [23], 90: ["Hi"], 25: [54]}  # 1
for val in a.values():  # 2
    print(str(val)[1:-1]   ':') # 3, 4
  1. Formatting.
  2. Using dict.values() since you're only using the values anyway.
  3. We manually convert each list to their string representation and then lop off the [ and ] using slicing.
  4. print always returns None. It's useless to assign that to hrs.

CodePudding user response:

Turn the list into a string before calling print:

a={"hello":[23,],90:["Hi",],25:[54,]}
for i in a:
    print(", ".join(map(str, a[i])), ": ")
  • Related