Python/공부내용

Python 공부내용 21.09.28. Python - Dictionary

HappyFrog 2021. 9. 28. 23:59

W3Schools의 Python Tutorial을 보며 해석하고 정리한 글입니다.

오역이 존재할 수 있습니다

저도 파이썬은 처음이니 가볍게 봐주세요 :D 

W3Schools


파이썬 딕셔너리

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

 

딕셔너리

딕셔너리는 값이 키 : 밸류(값)의 쌍으로 이루어진 데이터를 저장할 때 사용합니다.

 

딕셔너리는 순서가 있고 가변적이지만 중복값은 허용하지 않습니다.

 

참고 : 파이썬 3.7에서는 딕셔너리에 순서가 있지만, 그 이하의 버전에서는 딕셔너리에 순서는 없습니다.

 

딕셔너리는 중괄호로 생성하며 키와 밸류(값)를 갖습니다.

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

print(thisdict)

▲ 결과값 // x : y 가 하나의 아이템이 됩니다.

딕셔너리 아이템

딕셔너리의 아이템들은 순서가 있고 가변적이며 중복값을 허용하지 않습니다.

 

딕셔너리의 아이템들은 키 : 밸류의 쌍으로 존재하며 키의 이름을 사용함으로서 참조될 수 있습니다.

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

print(thisdict["brand"])

▲ 결과값

 

질서가 있는가 없는가?

질서가 있다는 뜻은 순서가 있다는 의미이며 이는 인덱스나 순서에 따라 참조할 수 있다는 의미입니다.

반면 질서가 없다면 인덱스나 순서를 사용하여 참조할 수 없습니다.

 

중복값 불허

딕셔너리는 같은 키를 가진 복수의 아이템을 허용하지 않습니다.

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

print(thisdict)

▲ 결과값 // 중복되는 값은 가장 최근에 읽은 값으로 덮어씌워집니다

 

딕셔너리의 길이 구하기

딕셔너리가 얼마나 많은 아이템을 가지고있는지를 알고 싶다면  len()  함수를 사용하면 됩니다.

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

print(len(thisdict))
print(thisdict)

▲ 결과값 // "x : y" 라는 "키 : 밸류" 쌍이 하나의 아이템으로 길이는 3입니다

 

딕셔너리 아이템들로 가능한 데이터 타입들

딕셔너리의 값으로 들어가는 아이템들은 모든 타입이 가능합니다.

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

print(thisdict)

▲ 결과값 // 리스트도 값으로 들어갈 수 있습니다

딕셔너리의 데이터 타입

딕셔너리의 데이터 타입 : 

<class 'dict'>
thisdict = {
    "brand" : "Ford",
    "model" : "Mustang",
    "year" : 1964,
    "colors" : ["red", "white", "blue"]
}

print(type(thisdict))

▲ 결과값


파이썬 - 딕셔너리 아이템들에 접근하기

아이템들에 접근하기

당신은 중괄호 안에 키 이름을 참조함으로써 아이템에 접근할 수 있습니다.

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

print(thisdict["model"])

▲ 결과값

 

그리고  get()  메서드를 사용해도 같은 결과를 얻을 수 있습니다

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

x = thisdict.get("model")
print(x)

▲ 결과값

 

키 받아오기

 key()  메서드를 사용하면 딕셔너리의 모든 키들을 리스트형식으로 받을 수 있습니다.

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

x = thisdict.keys()
print(x)

▲ 결과값

 

키로 이루어진 리스트는 딕셔너리의 키값을 보여주는 것이므로 딕셔너리에 변화를 가하면 리스트에 반영됩니다.

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

x = car.keys()

print(x)    # 변경 전

car["color"] = "white"

print(x)    # 변경 후

▲ 결과값

 

값 얻기

 values()  메서드는 딕셔너리의 모든 밸류(값)들을 리스트형식으로 반환합니다.

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

x = thisdict.values()

print(x)

▲ 결과값

 

이 값의 리스트 또한 딕셔너리의 값들을 보여주는 것이므로 딕셔너리에 가해지는 어떠한 변화도 리스트에 반영됩니다.

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

x = car.values()

print(x)    # 변경 전

car["year"] = 2020

print(x)    # 변경 후

▲ 결과값

 

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

x = car.values()

print(x)    # 변경 전

car["color"] = "red"

print(x)    # 변경 후

▲ 결과값

 

아이템 받아오기

 items()  메서드를 사용하면 딕셔너리의 각각의 아이템들을 리스트 안의 튜플 형식으로 받아올 수 있습니다.

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

x = thisdict.items()

print(x)

▲ 결과값

 

받아온 리스트는 딕셔너리의 아이템을 보여주는 것이므로 어떠한 변화라도 아이템 리스트에 반영됩니다.

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

x = thisdict.items()

print(x)    # 변경 전

thisdict["year"] = 2020

print(x)    # 변경 후

▲ 결과값

 

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

x = thisdict.items()

print(x)    # 변경 전

thisdict["color"] = "red"

print(x)    # 변경 후

▲ 결과값

 

키가 존재하는지 확인하기

특정한 키가 딕셔너리 안에 존재하는지를 확인하려면  in  키워드를 사용하면 됩니다

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

if "model" in thisdict:
    print("Yes, 'model' is one of the keys in the thisdict dictionary")

▲ 결과값


파이썬 - 딕셔너리 아이템 변경하기

밸류(값) 변경하기

당신은 특정한 아이템 키 이름을 참조하여 아이템의 밸류를 변경할 수 있습니다.

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

thisdict["year"] = 2021

print(thisdict)

▲ 결과값

 

딕셔너리 갱신하기

 update()  메서드는 주어진 요소로 딕셔너리의 아이템들을 갱신합니다.

 

요소는 딕셔너리 또는 "키 : 밸류:"쌍을 가진 iterable 객체여야 합니다.

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

thisdict.update({"year" : 2020})

print(thisdict)

▲ 결과값


파이썬 - 딕셔너리 아이템 추가하기

아이템 추가하기

새로운 키를 매기고 값을 할당함으로써 딕셔너리에 아이템을 추가할 수 있습니다.

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

thisdict["color"] = "red"

print(thisdict)

▲ 결과값

 

딕셔너리 갱신하기

 update()  메서드는 주어진 요소로 딕셔너리의 아이템을 갱신합니다. 만약 아이템이 존재하지 않는다면 주어진 요소는 아이템으로 새롭게 추가됩니다.

 

요소는 딕셔너리 또는 "키 : 밸류" 쌍을 이루는 iterable 객체여야 합니다.

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

thisdict.update({"color" : "red"})

print(thisdict)

▲ 결과값


파이썬 - 딕셔너리 아이템 제거하기

아이템 지우기

딕셔너리에서 아이템을 지우는 메서드는 여럿 존재합니다.

 

 pop()  메서드는 지정한 키 이름값을 가진 아이템을 삭제합니다.

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

thisdict.pop("model")

print(thisdict)

▲ 결과값

 

 popitem()  메서드는 마지막으로 삽입된 아이템을 삭제합니다. (3.7버전 이전은 무작위 아이템을 하나 삭제합니다)

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  키워드는 딕셔너리를 통째로 지울 수 있습니다.

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

del thisdict

print(thisdict)

▲ 결과값

 

 clear()  메서드는 딕셔너리를 비워줍니다.

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

thisdict.clear()

print(thisdict)

▲ 결과값


파이썬 - 딕셔너리 반복하기

딕셔너리를 통해 반복하기

당신은  for  문을 사용하여 딕셔너리를 반복할 수 있습니다.

 

딕셔너리를 반복할 때는 반환 값은 딕셔너리의 키들이지만 밸류를 반환하게 하는 메서드들도 존재합니다.

 

딕셔너리 안의 모든 키값을 하나하나 출력하는 방법 :

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

for x in thisdict:
    print(thisdict[x])

▲ 결과값

 

 key()  메서드 사용

 

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

for x in thisdict.keys():
    print(x)

▲ 결과값

 

 

밸류들을 각각 출력하는 방법 :

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

for x in thisdict:
    print(thisdict[x])

▲ 결과값

 

 values()  메서드 사용

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

for x in thisdict.values():
    print(x)

▲ 결과값

 

 items()  메서드를 사용하여 키와 밸류를 모두 반복하기

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

for x, y in thisdict.items():
    print(x, y)

▲ 결과값


파이썬 - 딕셔너리 복사하기

딕셔너리 복사하기

당신은 단순하게  dict2 = dict1  라는 식으로 작성하여 딕셔너리를 복사할 수 없습니다. 왜냐하면  dict2  dict1  의 참조가 될 뿐이고 이는  dict1  에서의 변화가  dict2  에 자동적으로 영향을 주게됩니다.

 

딕셔너리를 복사하는 데는 여러가지 방법이 있습니다. 그 중 하나의 방법은 빌트인 딕셔너리 메서드인  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)

▲ 결과값


파이썬 - 중첩된 딕셔너리들(nested dictionaries)

중첩된 딕셔너리들(nested dictionaries)

딕셔너리는 딕셔너리를 아이템으로서 가질 수 있습니다. 이것을 딕셔너리들의 중첩(nested dictionaries)이라고 부릅니다.

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

▲ 결과값

 

또는 세 딕셔너리를 새로운 딕셔너리에 더해주는 방법도 있습니다.

child1 = {
        "name" : "Emil",
        "year" : 2004
    }

child2 = {
        "name" : "Tobias",
        "year" : 2007
    }

child3 = {
        "name" : "Linus",
        "year" : 2011
    }

myfamily = {
    "child1" : child1,
    "child2" : child2,
    "child3" : child3
}

print(myfamily)

▲ 결과값 // 딕셔너리의 키 값인 "child1" 같은 이름은 스트링으로 지정해주는 모습입니다


파이썬 딕셔너리 메서드

딕셔너리 메서드

파이썬에서 딕셔너리로 사용할 수 있는 빌트인 딕셔너리 메서드들이 있습니다.

출처 W3School

 

댓글수0