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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With