如果我有一个字典,每个键有两个值,我如何选择一个值?
例如:
dict = {'Banana' : {'price': 7, 'Color' : "yellow"},
'Apple' : {'price' : 8, 'Color': "green"}, 'Orange' :{'price' : 6, 'Color': "orange"}}
当我想知道每种水果的价格时,我该怎么问?
for i in range (len(dict)):
dict[i][0]
这是正确的解决方案吗?
答案 0 :(得分:3)
使用其他for
循环,我怀疑in range
是否有效:
for fruit, data in dict.iteritems():
print(fruit + " costs " + str(data['price']))
编辑以回答评论:
for i in range (len(d)): d.keys[i] == d.keys[i+1]:
和for i in d.keys: d[i] == d[i+1]
无法使用,您需要多写一点:
d = dict.keys()
for i in range(len(d)):
if i+1 < len(d) and d[i] == d[i+1]:
#do stuff
答案 1 :(得分:3)
这应该有效:
for fruit, info in dict.iteritems():
print "%s: Colour %s - Price %d" % (fruit, info['Color'], info['price'])
答案 2 :(得分:0)
另一个选项是itervalues()和list comprehensions
>>> d = {'Banana' : {'price': 7, 'Color' : "yellow"},
... 'Apple' : {'price' : 8, 'Color': "green"}, 'Orange' :{'price' : 6, 'Color': "orange"}}
>>> [i['price'] for i in d.itervalues()]
[6, 7, 8]