단비의 코딩 공부 blog

[Python] study 4주차 본문

Python

[Python] study 4주차

황굽달 2024. 4. 17. 10:07
Python Dictionaries

 

dictionaries는 데이터를 키 : 값 쌍으로 저장하는데 사용된다.

순서가 지정되고 변경 가능하며 중복이 허용되지 않는 모음이다.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

출력 결과:

 

dictionaries는 변경 가능하다. 즉, 생성된 후 항목을 변경, 추가 또는 제거할 수 있다.

중복은 허용가능하지 않기때문에 동일한 키를 가진 두 개의 항목은 있을 수 없다.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "year": 2020
}
print(thisdict)

출력 결과:

 

dictionaries 항목의 값은 모든 데이터 유형이 될 수 있다.

thisdict = {
  "brand": "Ford",
  "electric": False,
  "year": 1964,
  "colors": ["red", "white", "blue"]
}

출력 결과:

 

Python에서 dictionaries은 데이터 유형이 'dict'인 객체로 정의된다.

type()메서드를 사용한다.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(type(thisdict))

출력 결과:

 

dict() 생성자를 사용하여 사전을 만드는 것도 가능하다.

thisdict = dict(name = "John", age = 36, country = "Norway")

print(thisdict)

출력 결과:

 

Python - Access Dictionary Items

 

대괄호 안에 있는 키 이름을 참조하여 dictionaries 항목에 엑세스 할 수 있다.

get() 메서드를 사용하면 동일한 결과를 얻을 수 있다.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"]


x = thisdict.get("model")

출력 결과:

 

keys() 메서드는 dictionaries에 있는 모든 키 목록을 반환한다.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

x = thisdict.keys()

print(x)

출력 결과:

 

새 항목을 추가하고 키 목록도 업데이트 할 수 있다.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

출력 결과:

 

Python - Change Dictionary Items

 

키 이름을 참조하여 특정 항목의 값을 변경할 수 있다.

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

thisdict["year"] = 2018

print(thisdict)

출력 결과:

 

update() 메서드는 사용하면 dictionaries를 업데이트 할 수있다.

인수는 dictionaries이거나 키:값과 같이 쌍이 있는 반복 가능한 객체여야한다.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020})

print(thisdict)

출력 결과:

 

Python - Remove Dictionary Items

 

dictionaries에서 항목을 제거하는 방법에는 여러가지가 있다.

pop() 메서드는 지정된 키 이름을 가진 항목을 제거한다.

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)

출력 결과:

 

popitem() 메서드는 마지막으로 삽입된 항목을 제거한다.

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.popitem()
print(thisdict)

 

출력 결과:

 

키워드 del은 지정된 키 이름을 가진 항목을 제거한다.

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict["model"]
print(thisdict)

출력 결과:

 

키워드 del은 dictionaries을 완전히 삭제할 수도 있다.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

출력 결과:

 

clear() 메서드는 dictionaries를 비운다.

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict)

출력 결과:

Python - Loop Dictionary

 

for를 사용하여 dictionaries을 반복할 수 있다.

모든 이름을 하나씩 출력한다.

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
for x in thisdict:
  print(x)

출력 결과:

 

모든값을 하나씩 인쇄한다.

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
for x in thisdict:
  print(thisdict[x])

출력 결과:

 

values() 메서드와 keys() 메서드를 사용하여 dictionaries 값을 반환할 수 있다.

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
for x in thisdict.values():
  print(x)


thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
for x in thisdict.keys():
  print(x)

출력 결과:

 

items() 메서드를 사용하면 키와 값을 모두 반환한다.

thisdict =	{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
for x, y in thisdict.items():
  print(x, y)

출력 결과:

Python - Copy Dictionaries

 

copy() 메서드를 사용하여 복사본을 만들 수 있다.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = thisdict.copy()
print(mydict)

출력 결과:

 

내장기능 dict() 함수를 사용하여 복사본을 만들 수 있다.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = dict(thisdict)
print(mydict)

출력 결과:

Python - 중첩 Dictionaries

 

dictionaries에는 dictionaries이 포함될 수 있으며 이를 중첩 사전이라고 한다.

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

print(myfamily)

출력 결과:

 

중첩된 dictionaries항목에 엑세스 하려면 외부 dictionaries부터 시작하여 사용한다.

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

print(myfamily["child2"]["name"])

출력 결과:

 

item() 을 사용하여 중첩된 dictionaries 을 반복할 수 있다.

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

for x, obj in myfamily.items():
    print(x)
    
    for y in obj:
        print(y + ':', obj[y])

출력 결과:

Python - Dictionary Methods

 

Method           Description

clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

 

'Python' 카테고리의 다른 글

[Python] study 5주차  (1) 2024.04.26
[Python] study 3주차  (0) 2024.04.12
[Python] study 2주차  (0) 2024.04.05
[Python] study 1주차  (0) 2024.04.04