초보자를 위한 Python 사전에 대한 완전한 가이드

목차



Introduction
Definition
Creating Python dictionary
Accessing dictionary items
Changing and Adding Values
Removing Items
Looping through a Dictionary
Dictionary Methods
To Sum It Up

소개

Python Dictionary is a composite data type. It is an ordered collection of data values that is used to store them. Each Dictionary consists of key-value pairs that are enclosed in curly braces. The keys are unique for each dictionary. The main operations that can be performed on a Dictionary are storing any value with some corresponding key and extracting the value with help of the key. A Dictionary can also be changed as it is mutable. Moreover, there are a lot of useful built-in methods!


정의

Python dictionary is a collection of items. Each dictionary consists of a collection of key-value pairs. Every key-value pair maps the key to its associated value allowing the dictionary to retrieve values. The key is separated from its value by a colon (:) while the items are separated by commas. A dictionary is enclosed in curly braces. An empty dictionary can be written with two curly braces, like this: {}.

In Python 3.6 and earlier versions, dictionaries were unordered but have been modified to maintain insertion order with the release of Python 3.7 making them an ordered collection of data values.


파이썬 사전 만들기

Creating a dictionary is no rocket science. It is as simple as placing items inside curly braces {} that are separated by commas. As discussed above, an item has a key and a corresponding value that is expressed as a pair like this: (key: value). The values can be of any data type and can also repeat but the keys must be unique and of immutable type e.g. string, number, or tuple with immutable elements.

Example:

# An empty dictionary
my_dict = {}
print(my_dict)

# A dictionary that has integer keys
my_dict = {1: 'apple', 2: 'mango'}
print(my_dict)

# A dictionary with mixed type keys
my_dict = {'name': 'Ayesha', 1: [5, 10, 13]}
print(my_dict)

Output:

{}
{1: 'apple', 2: 'mango'}
{'name': 'Ayesha', 1: [5, 10, 13]}

A Dictionary can also be created by using the built-in function dict().

Example:

# Creating a Dictionary with dict() method
Dict = dict({1: 'Ayesha', 2: 'Sahar'})
print(Dict)

Output:

{1: 'Ayesha', 2: 'Sahar'}

사전 항목 액세스

In order to access dictionary elements, you can use square brackets along with the key to obtain its value. Another method called get() also helps in accessing any element from a dictionary.

Example:

dict = {'Name': 'Ali', 'Age': 8, 'Grade': '3'}

# Acessing items using []
print(dict['Name'])
print(dict['Age'])

# Acessing items using .get()
print(dict.get('Grade'))

Output:

Ali
8
3

값 변경 및 추가

Python Dictionaries are mutable (changeable). New items can be added or the value of existing items can be easily changed using an assignment operator. If the specified key is present in the dictionary, then the existing value gets updated. If not, a new (key: value) pair is added to the dictionary.

Example:

thisdict =  {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}

# Changing Values

thisdict["Age"] = 23
print(thisdict)

# Adding values

thisdict['City'] = 'London'
print(thisdict)

*Output: *

{'Name': 'Zahid', 'Age': 23, 'Occupation': 'Manager'}
{'Name': 'Zahid', 'Age': 23, 'Occupation': 'Manager', 'City': 'London'}

항목 제거

Several methods can be used to remove items from a dictionary.

1. 팝()



이 메서드는 지정된 키 이름을 가진 항목을 제거합니다.

예시:

thisdict =  {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}

thisdict.pop("Age")
print(thisdict)


산출:

{'Name': 'Zahid', 'Occupation': 'Manager'}


2. 포아이템()



이 메서드는 마지막으로 삽입된 항목을 제거합니다(Python 버전 3.6 이하에서는 임의의 항목이 대신 제거됨).

예시:

thisdict =  {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}

thisdict.popitem()
print(thisdict)


산출:

{'Name': 'Zahid', 'Age': 21}


3. 델



이 키워드는 지정된 키 이름을 가진 항목을 제거하거나 사전을 완전히 삭제할 수도 있습니다.

예시:

# Deleting a specified item
thisdict =  {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}
del thisdict["Age"]
print(thisdict)

# Deleting the whole dictionary 
del thisdict
print(thisdict)


산출:

{'Name': 'Zahid', 'Occupation': 'Manager'} 

#Here we get an error because the dictionary no longer exists!
Traceback (most recent call last):
  File "c:\Users\Dell\Desktop\Dictionary_demo.py", line 11, in <module>
    print(thisdict)
NameError: name 'thisdict' is not defined



4. 클리어()



이 메서드는 사전을 비웁니다.

예시:

thisdict =  {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}
thisdict.clear()
print(thisdict)


산출:

{}



사전 반복하기

We can loop through a dictionary using for loop. After looping, keys of a dictionary are returned. But through other methods, we can return the values too! Here is an example of printing all keys of a dictionary:

Example:

thisdict =  {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
} 
for x in thisdict:
  print(x)

Output:

Name
Age
Occupation

Here’s how to print all values in the dictionary:

Example:

thisdict =  {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
} 
for x in thisdict:
  print(thisdict[x])

Output:

Zahid
21
Manager

By using the items() method, we can loop through both keys and values. Cool, right?

Example:

thisdict =  {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
} 
for x, y in thisdict.items():
  print(x, y)

Output:

Name Zahid
Age 21
Occupation Manager

사전 방법

Here’s a list of some useful dictionary methods:

1. 모두()



모든 키가 True이거나 사전이 비어 있으면 True를 반환합니다.

2. 아무()



키가 true이면 True를 반환하고 사전이 비어 있으면 False를 반환합니다.

3. 렌()



사전의 길이(사전 항목 수)를 반환합니다.

4. 업데이트()



지정된 키-값 쌍으로 사전을 업데이트합니다.

5. 정렬()



사전에 있는 모든 키의 정렬된 새 목록을 반환합니다.

6. 복사()



사전의 정확한 복사본을 반환합니다.

7. 유형()



전달된 변수의 데이터 유형을 반환합니다.


그것을 요 ​​약하기...........

• Python Dictionary is a mutable, ordered collection of data values present in the form of key-value pairs.

• Dictionary items can be accessed through square brackets or by using the get() method.

• Values can be added in a Dictionary by using the assignment operator.

• Items can be removed by using pop(), popitem(), del and clear() methods.

• You can loop through the Dictionary to print either the keys or the values, or you can also print both by using the items() method.


Let's connect!

Github

좋은 웹페이지 즐겨찾기