






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 dilithium 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.
집합은 단순한 데이터 구조이며,
고유한 요소를 수집하는 주요 용도가 있습니다.
우리의 다음 데이터 구조,
사전은 더 유연합니다.
목록 및 집합과 같은 단일 객체를 저장하는 대신,
사전은 요소, 키 및 값의 쌍을 저장합니다.
이 예에서는 사전을 정의합니다.
여기서 키는 요소 이름이고,
값은 해당 원자 번호입니다.
사전에서 값을 찾을 수 있습니다.
키를 묶는 대괄호를 사용합니다.
대괄호를 사용하여 사전에 새 값을 삽입할 수도 있습니다.
여기에 리튬을 추가하고,
값을 3으로 지정합니다.
사전 키는 목록 인덱스와 유사합니다.
데이터 구조에서 요소를 선택할 수 있습니다.
키를 대괄호 안에 넣습니다.
목록과 달리 딕셔너리는 정수뿐만 아니라 불변 유형의 키를 가질 수 있습니다.
요소 사전은 키에 문자열을 사용합니다.
그러나 모든 키가 동일한 유형일 필요는 없습니다.
값이 사전에 있는지 여부를 확인할 수 있습니다.
값이 목록 또는 집합에 있는지 여부를 확인하는 것과 같은 방식으로
in 키워드로.
in을 사용하여 확인할 수 있습니다.
키를 찾기 전에 사전에 키가 있는지 여부.
가능성이 있다면,
열쇠가 없다는 것입니다.
Mithril은 요소 사전의 일부가 아니므로 false가 인쇄됩니다.
사전에는 관련 방법이 있습니다.
“get”도 유용합니다.
“Get”은 사전에서 값을 찾습니다.
그러나 대괄호와 달리
“get”은 아무 것도 반환하지 않거나 선택한 기본값을 반환합니다.
키를 찾을 수 없는 경우.
딜리튬은 사전에 없습니다.
그래서 아무 것도 반환되지 않고 인쇄됩니다.
조회가 때때로 실패할 것으로 예상되는 경우
Get은 일반 대괄호 조회보다 더 나은 도구일 수 있습니다.
오류가 프로그램을 충돌시킬 수 있기 때문에 좋지 않습니다.
“is”연산자를 사용하여 키가 아무 것도 반환하지 않는지 확인할 수 있습니다.
또는 “is not”을 사용하여 반대를 확인할 수 있습니다.
이를 ID 연산자라고 합니다.
ID 연산자에 대해 자세히 알아볼 것입니다.
같음을 사용하는 것과 어떻게 다른지,
또는 같지 않음, 뒤따르는 퀴즈의 비교 연산자.
Dictionaries And Identity Operators
Dictionaries
A dictionary is a mutable data type that stores mappings of unique keys to values. Here’s a dictionary that stores elements and their atomic numbers.
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
Dictionaries can have keys of any immutable type, like integers or tuples, not just strings. It’s not even necessary for every key to have the same type! We can look up values or insert new values in the dictionary using square brackets that enclose the key.
print(elements["helium"]) # print the value mapped to "helium" elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary
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. Dicts 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 isn’t found.
print("carbon" in elements) print(elements.get("dilithium"))
This would output:
True None
Carbon is in the dictionary, so True is printed. Dilithium isn’t in our dictionary so None is returned by get
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.
Identity Operators
Keyword | Operator |
---|---|
is | evaluates if both sides have the same identity |
is not | evaluates if both sides have different identities |
You can check if a key returned None with the is
operator. You can check for the opposite using is not
.
n = elements.get("dilithium") print(n is None) print(n is not None)
This would output:
True False
댓글을 달려면 로그인해야 합니다.