Python的字典的items(), keys(), values()都返回一个list
-
>>> dict = { 1 : 2, 'a' : 'b', 'hello' : 'world' }
-
>>> dict.values()
-
['b', 2, 'world']
-
>>> dict.keys()
-
['a', 1, 'hello']
-
>>> dict.items()
-
[('a', 'b'), (1, 2), ('hello', 'world')]
-
>>>
例如:
现在你有一家人的账本,算一下这一家子一共有多少钱?
note = {"Mom" : 14500, "Dad" : 24355, "Children" : 4560}
方法一:使用values()
-
note = {"Mom" : 14500, "Dad" : 24355, "Children" : 4560}
-
familySavings = 0
-
for saving in note.values():
-
familySavings = familySavings + saving
-
-
print familySavings
方法二:使用items()
-
note = {"Mom" : 14500, "Dad" : 24355, "Children" : 4560}
-
familySavings = 0
-
for a,saving in note.items():
-
familySavings = familySavings + saving
-
-
print familySavings
方法三:使用sum
-
note = {"Mom" : 14500, "Dad" : 24355, "Children" : 4560}
-
print sum(note.values())
阅读(1168) | 评论(0) | 转发(0) |