Python/Python Basic Lesson

Python Programming Basic - 7. 딕셔너리 함수

Pydole 2020. 3. 2. 20:38

 

 


items() : 사전의 키, 값 모두 return
      

dic = {'a':1,'b':2,'c':3} 

print(dic.items())



# for문을 이용한 key, value 반복 추출

for key, value in dic.items():
    print(key, value)
    


a 1
b 2
c 3





key() : 사전의 키 return
      

dic = {'a':1,'b':2,'c':3} 

print(dic.keys())



dict_keys(['a', 'b', 'c'])


# for문을 활용한 key 

for key in dic.keys():
    print(key)



a
b
c





values() : 사전의 값 return
      

dic = {'a':1,'b':2,'c':3} 

print(dic.values())



dict_values([1, 2, 3])


# for문

for key in dic.values():
    print(key)




1
2
3





get() : 사전에서 키의 값을 리턴
      

dic = {'a':1,'b':2,'c':3} 

print(dic.get('a'))
print(dic.get('d', 10) # 키가 없으면, 지정 값이 10을 반환


1
10

 

dic = {'a':1,'b':2,'c':3} 

print(dic.get('d', '값이 없습니다'))



값이 없습니다

 

 

def func():
    return '값이 없습니다'

dic = {'a':1,'b':2,'c':3} 

print(dic.get('d', func()))



값이 없습니다

 

 

 

 

 

del : 키 삭제하기

 

dic = {'a':1,'b':2,'c':3} 

del dic['a']   # 'a' :  1 삭제
print(dic)



{'b': 2, 'c': 3}

 

 

 

pop() : 키를 삭제하고, 삭제된 밸류값을 리턴

 

dic = {'a':1,'b':2,'c':3} 

print(dic.pop('a'))       # 'a' 키를 삭제하고, 1 밸류값 리턴

1

 

dic = {'a':1,'b':2,'c':3} 

dic.pop('d','not')         # 키가 없을 때에, 리턴값을 지정

'not'

 

 

삭제된  key, value 값 남기기

 

def func(value):
    return key, value

dic = {'a':1,'b':2,'c':3} 

key = 'c'
func(dic.pop(key))



('c', 3)

 

 

 




clear : 사전 초기화
      

dic = {'a':1,'b':2,'c':3} 
dic.clear() 

print(dic)



{}



 

key 나 value 가 존재하는 지 확인

 

dic =  {'a':1,'b':2,'c':3} 
print('b' in dic.keys())

dic =  {'a':1,'b':2,'c':3} 
print(1 in dic.values())



True
True