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
答案 0 :(得分:13)
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))
答案 1 :(得分:2)
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))
答案 2 :(得分: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
.
答案 3 :(得分:1)
你可以这样做:
spam = {'color': 'red', 'age': '42','planet of origin': 'mars'}
for k in spam.keys():
print(k+ ":" +spam[k] )
答案 4 :(得分:1)
for k in spam:
print(str(k)+':'+str(spam[k]))
答案 5 :(得分:0)
尝试以下代码,
s={'name': 'you', 'number': 123, 'password': '555', 'amt': 800}
for i in s:
print(i,"=>" ,s[i])
答案 6 :(得分:-1)
按照mathias711的建议去做!
实际上你的代码用str(spam.values())
做的是写下dict的所有值。
通过str(spam[k])
,您可以获得与密钥“k”相关联的值。在dict'垃圾邮件'。
如果您确实希望输出按特定顺序排列,则应该有一个列表,其中所有键按此顺序排序,因为默认情况下不会对字典进行排序。
你的代码看起来像这样:
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]))