欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

coursesa课程 Python 3 programming Dictionary methods 字典的方法

程序员文章站 2024-03-23 12:58:22
...

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))