1

so i have python homework and had to print values and keys, but with "->" between them.

d = {'x': 10, 'y': 20, 'z': 30} 

this is values and keys and had to print it like this

x -> 10 y -> 20 z -> 30 

i tried to do it like this

for key, value in d.items(): print(key + "->" + value) 

but it tells me that "an only concatenate list (not "str") to list" what can i do?

1
  • 1
    Did you mean: print(f'{key} -> {value}')? Commented Dec 6, 2020 at 12:08

4 Answers 4

2

Try this: replace + with ,

print(key, "->", value) 
Sign up to request clarification or add additional context in comments.

Comments

1

You could use str constructor.

for key, value in d.items(): print(key + "->" + str(value)) ^^^^^^^^ 

Another approach could be using string interpolation.

for key, value in d.items(): print(f'{key} -> {value}') 

Comments

0

Another option is using format

for key, value in d.items(): print("{}->{}".format(key, value)) 

You can also solve this problem in one line:

print('\n'.join(["{}->{}".format(key, value) for key, value in d.items()])) 

Result:

x->10 y->20 z->30 

Comments

0

Use the "items" method in the dictionary class:

for i,v in d.items(): print(i, '->', v) 

Make sure you're using a comma (,) and not a plus sign (+) between the variables of your one row.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.