Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the dict with “key: value” pairs in a for loop

I want to iterate through the dict, spam, and print the result in the format of "key: value". There’s something wrong with my code that’s producing a different result.

Is there any ways of correcting the output? And why I’m I getting this output?

spam = {'color': 'red', 'age': '42', 'planet of origin': 'mars'}

for k in spam.keys():
    print(str(k) + ': ' + str(spam.values()))

The result in getting:

color: dict_values(['red', '42', 'mars'])
age: dict_values(['red', '42', 'mars'])
planet of origin: dict_values(['red', '42', 'mars'])

The expected result:

color: red
age: 42
planet of origin: mars
like image 354
Newb69420 Avatar asked Apr 13 '17 14:04

Newb69420


1 Answers

You should instead be using dict.items instead, since dict.keys only iterate through the keys, and then you're printing dict.values() which returns all the values of the dict.

spam = {'color': 'red', 'age': '42','planet of origin': 'mars'}

 for k,v in spam.items():
     print(str(k)+': '  + str(v))
like image 186
Taku Avatar answered Oct 27 '22 00:10

Taku