달나라 노트

Python Basic : dictionary values(), keys(), items() (dictionary key 얻기, dictionary value 얻기, dictionary item 얻기) 본문

Python/Python Basic

Python Basic : dictionary values(), keys(), items() (dictionary key 얻기, dictionary value 얻기, dictionary item 얻기)

CosmosProject 2022. 10. 11. 00:56
728x90
반응형

 

 

 

Syntax

dictionary.keys()

 

dictionary에 존재하는 모든 key를 return 합니다.

 

 

 

 

dictionary.values()

 

dictionary에 존재하는 모든 value를 return 합니다.

 

 

 

 

dictionary.items()

 

dictionary를 구성하는 모든 key, value 값을 tuple로 묶어서 return 합니다.

 

 

 

 

 

 

 

 

 

예시를 봅시다.

 

dict_test = {
    'key1': 1,
    'key2': 2,
    'key3': 3
}

print(dict_test.keys())



-- Result
dict_keys(['key1', 'key2', 'key3'])

 

- dict_test.keys()

dict_test에 keys() method를 적용했습니다.

그 결과 값을 보니 dict_keys(['key1', 'key2', 'key3']) 입니다.

 

dictionary에 존재하는 모든 key값을 dictionary keys type으로 묶어서 return한 것입니다.

 

 

 

dict_test = {
    'key1': 1,
    'key2': 2,
    'key3': 3
}

for i in dict_test.keys():
    print(i)



-- Result
key1
key2
key3

 

keys() method의 return 값도 iterable type이기 때문에 위처럼 for loop 등의 반복문에 적용할 수 있습니다.

 

 

 

 

 

 

dict_test = {
    'key1': 1,
    'key2': 2,
    'key3': 3
}

print(dict_test.values())



-- Result
dict_values([1, 2, 3])

 

- dict_test.values()

dict_test에 values() method를 적용했습니다.

그 결과 값을 보니 dict_values([1, 2, 3]) 입니다.

 

dictionary에 존재하는 모든 value값을 dictionary values type으로 묶어서 return한 것입니다.

 

 

 

 

 

dict_test = {
    'key1': 1,
    'key2': 2,
    'key3': 3
}

for i in dict_test.values():
    print(i)



-- Result
1
2
3

 

values() method의 return 값도 iterable type이기 때문에 위처럼 for loop 등의 반복문에 적용할 수 있습니다.

 

 

 

 

 

 

 

 

 

 

dict_test = {
    'key1': 1,
    'key2': 2,
    'key3': 3
}

print(dict_test.items())



-- Result
dict_items([('key1', 1), ('key2', 2), ('key3', 3)])

 

- dict_test.items()

dict_test에 items() method를 적용했습니다.

그 결과 값을 보니 dict_items([('key1', 1), ('key2', 2), ('key3', 3)]) 입니다.

 

dictionary에 존재하는 모든 요소들인 모든 key - value 쌍(pair)을 tuple로 묶고, 각각의 tuple을 dictionary items type에 담아서 return한 것입니다.

 

 

 

 

dict_test = {
    'key1': 1,
    'key2': 2,
    'key3': 3
}

for i in dict_test.items():
    print(i)



-- Result
('key1', 1)
('key2', 2)
('key3', 3)

 

items() method의 return 값도 iterable type이기 때문에 위처럼 for loop 등의 반복문에 적용할 수 있습니다.

 

 

 

 

dict_test = {
    'key1': 1,
    'key2': 2,
    'key3': 3
}

for i, j in dict_test.items():
    print(i)
    print(j)



-- Result
key1
1
key2
2
key3
3

 

items() method의 return값은 내부에 tuple이 존재하는 형태이므로 for loop에 변수를 i, j 2개로 잡아서 tuple로 묶인 key, value 값을 위 예시처럼 각각 받을 수도 있습니다.

 

 

 

 

 

 

728x90
반응형
Comments