coursesa课程 Python 3 programming Dictionary methods 字典的方法
Note
Technically, .keys(), .values(), and .items() don’t return actual lists. Like the range function described previously, in python 3 they return objects that produce the items one at a time, rather than producing and storing all of them in advance as a list. Unless the dictionary has a whole lot of keys, this won’t make a difference for performance. In any case, as with the range function, it is safe for you to think of them as returning lists, for most purposes. For the python interpreter built into this textbook, they actually do produce lists. In a native python interpreter, if you print out type(inventory.keys()), you will find that it is something other than an actual list. If you want to get the first key, inventory.keys()[0] works in the online textbook, but in a real python interpreter, you need to make the collection of keys into a real list before using [0] to index into it: list(inventory.keys())[0].
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
print('apples' in inventory)
print('cherries' in inventory)
if 'bananas' in inventory:
print(inventory['bananas'])
else:
print("We have no bananas")
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
print(inventory.get("apples"))
print(inventory.get("cherries"))
print(inventory.get("cherries",0))
上一篇: Python的一道面试题
下一篇: 一道sql面试题