Newb69420
Newb69420

Reputation: 99

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

Upvotes: 8

Views: 25903

Answers (7)

aditya
aditya

Reputation: 11

Try the below codes,

s={'name': 'you', 'number': 123, 'password': '555', 'amt': 800}


for i in s:
    print(i,"=>" ,s[i])

Upvotes: 1

RomainL.
RomainL.

Reputation: 1014

do as mathias711 propose you! In fact what your code do with str(spam.values()) is to write all the value of the dict. By doing str(spam[k]) you get the value associated with the key 'k' in the dict 'spam'. If you really want your output in a certain order you should have a list with all the keys sorted in this order because by default key of a dictionnary are not ordered.

which that your code look this way:

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

liste_ordered_for_output['color', 'age', 'planet of origin']


for key in liste_ordered_for_output:
    print(str(key)+': '  + str(spam[key]))

Upvotes: -1

Mathias711
Mathias711

Reputation: 6658

Change str(spam.values()) to spam[k]. The first option gives all values inside the dictionary, the second one yields the value belonging to the current key k.

Upvotes: 1

Astrom
Astrom

Reputation: 767

did you try?

for k in spam:
    print(str(k)+':'+str(spam[k]))

Upvotes: 1

Kedar Kodgire
Kedar Kodgire

Reputation: 492

You can do this:

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


for k in spam.keys():

    print(k+  ":"  +spam[k] )

Upvotes: 1

Taku
Taku

Reputation: 33714

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))

Upvotes: 26

brianpck
brianpck

Reputation: 8254

dict.values() returns a list of all the values in a dictionary. Why not do a key lookup?

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

Or even better:

for k, v in spam.items():
    print('{}: {}'.format(k, v))

Upvotes: 4

Related Questions