19 – L2 02 Dictionaries And Identiy Operators V35

Sets, are simple data structures, and they have one main use, collecting unique elements. Our next data structures, dictionaries, are more flexible. Rather than storing single objects like lists and sets do, dictionaries store pairs of elements, keys and values. In this example, we define a dictionary, where the keys are element names, and their values are their corresponding atomic numbers. We can look up values in the dictionary, by using square brackets enclosing a key. We can also insert new values into the dictionary, with square brackets. Here, we are adding lithium, and giving it a value of three. Dictionary keys are similar to list indices. We can select elements from the data structure, by putting the key in square brackets. Unlike lists, dictionaries can have keys of any immutable type, not just integers. The element dictionary uses strings for its keys. However, it’s not even necessary for every key to have the same type. We can check whether a value is in a dictionary, the same way we check whether a value is in a list or set, with the in keyword. We can use in to verify, whether a key is in the dictionary, before looking it up. If there’s a possibility, that the key is not there. Mithril, was not part of our elements dictionary, so false is printed. Dictionaries have a related method, that’s also useful, “get”. “Get” looks up values in a dictionary, but unlike square brackets, “get” returns none, or a default value of your choice, if the key is not found. The lithium is not in our dictionary, so none is returned, and then printed. If you expect lookups to sometimes fail, Get might be a better tool than normal square bracket lookups, because errors can crash your program, which isn’t good. You can check if a key return none with the “is” operator, or you can check for the opposite using “is not”. These are called identity operators. You will learn more about identity operators, and how they differ from using these equals to, or not equals to, comparison operators in the quizzes that follow.

Dr. Serendipity에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

Continue reading