7

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
Taku
  • 31,927
  • 11
  • 74
  • 85
Newb69420
  • 91
  • 1
  • 1
  • 9

7 Answers7

25

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))
Taku
  • 31,927
  • 11
  • 74
  • 85
4

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))
brianpck
  • 8,084
  • 1
  • 22
  • 33
1

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.

Mathias711
  • 6,568
  • 4
  • 41
  • 58
1

You can do this:

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


for k in spam.keys():

    print(k+  ":"  +spam[k] )
Kedar Kodgire
  • 482
  • 6
  • 22
1

did you try?

for k in spam:
    print(str(k)+':'+str(spam[k]))
Astrom
  • 767
  • 5
  • 20
1

Try the below codes,

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


for i in s:
    print(i,"=>" ,s[i])
Angel F Syrus
  • 1,984
  • 8
  • 23
  • 43
aditya
  • 11
  • 1
  • Welcome to Stack Overflow. Please see [this article on how to write good answers](https://stackoverflow.com/help/how-to-answer). Answers should be properly formatted, in your case, by using code blocks. Also, code is okay, but adding context to it (the reason behind it) is much more useful than the code alone. – James Mchugh Nov 30 '19 at 06:13
-1

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]))
RomainL.
  • 997
  • 1
  • 10
  • 24