728x90

dictionary.get(keyname, value

Scores = {'English':67, 'Maths':87}
print(Scores.get('English'))

# Output: 67

print(Scores.get('Physics'))

# Output: None

딕셔너리에 get 메서드를 하면 해당 key의 value 값을 반환해 주며 key가 존재하지 않을 때에는 None값을 반환한다.

 

이것을 조금 응용해서 리스트에 동일한 value가 몇개인지 딕셔너리 타입으로 나타내준다고 했을 때 

participant = ['lingo','nana','leo','nana','lingo']
dic ={}
for i in participant:
    if i not in dic.keys():
        dic[i] = 1
    else:
        dic[i] +=1
print(dic)
# ouput {'lingo': 2, 'nana': 2, 'leo': 1}
###########################
dic ={}
for x in participant:
	dic[x] = dic.get(x, 0) + 1  # d 딕셔너리에 x값이 있으면 1을 더해주고 x가 없으면 0 +1
print(dic)
# ouput {'lingo': 2, 'nana': 2, 'leo': 1}
728x90

+ Recent posts