Python의 딕셔너리는 여러가지 메소드를 통해 간편하게 사용할 수 있습니다. 딕셔너리 메소드를 활용하면 더욱 간편하고 효율적으로 데이터를 저장하고 관리할 수 있습니다.
dict.keys()
dict.keys()
메소드는 딕셔너리의 키를 반환합니다. 따라서, 딕셔너리의 키를 알고 싶을 때 사용할 수 있습니다.
Example
my_dict = {
'name': 'John',
'age': 20,
'gender': 'male'
}
keys = my_dict.keys()
print(keys)
위의 코드는 다음과 같이 출력됩니다.
dict_keys(['name', 'age', 'gender'])
dict.values()
dict.values()
메소드는 딕셔너리의 값을 반환합니다. 따라서, 딕셔너리의 값을 알고 싶을 때 사용할 수 있습니다.
Example
my_dict = {
'name': 'John',
'age': 20,
'gender': 'male'
}
values = my_dict.values()
print(values)
위의 코드는 다음과 같이 출력됩니다.
dict_values(['John', 20, 'male'])
dict.items()
dict.items()
메소드는 딕셔너리의 키와 값을 튜플로 묶은 값을 반환합니다. 따라서, 딕셔너리의 키와 값을 함께 알고 싶을 때 사용할 수 있습니다.
Example
my_dict = {
'name': 'John',
'age': 20,
'gender': 'male'
}
items = my_dict.items()
print(items)
위의 코드는 다음과 같이 출력됩니다.
dict_items([('name', 'John'), ('age', 20), ('gender', 'male')])
dict.get()
dict.get()
메소드는 딕셔너리의 키를 인자로 받아 해당 키에 대한 값을 반환합니다. 따라서, 딕셔너리의 값을 알고 싶을 때 사용할 수 있습니다.
Example
my_dict = {
'name': 'John',
'age': 20,
'gender': 'male'
}
name = my_dict.get('name')
print(name)
위의 코드는 다음과 같이 출력됩니다.
John
dict.update()
dict.update()
메소드는 딕셔너리의 값을 업데이트합니다. 따라서, 딕셔너리의 값을 업데이트할 때 사용할 수 있습니다.
Example
my_dict = {
'name': 'John',
'age': 20,
'gender': 'male'
}
my_dict.update({'name': 'Jane'})
print(my_dict)
위의 코드는 다음과 같이 출력됩니다.
{'name': 'Jane', 'age': 20, 'gender': 'male'}
딕셔너리 메소드를 활용하면 더욱 간편하고 효율적으로 데이터를 저장하고 관리할 수 있습니다. 이번 글에서는 dict.keys()
, dict.values()
, dict.items()
, dict.get()
, dict.update()
메소드를 소개하였습니다. 이 메소드들을 활용하면 딕셔너리를 더욱 효율적으로 관리할 수 있습니다.