TIL[46]. Python_ Looping Dictionary

jake.log·2020년 8월 23일
0

Python

목록 보기
28/39

28.Looping Dictionary

dictionary도 for 반복구문(loop)을 사용하여 요소 하나 하나를 가지고 반복되는 로직을 실행 시킬 수 있다.

dictionary를 사용한 for 반복구문에서는 각 요소의 key만 리턴을 한다.
그리고 해당 key를 가지고 값을 읽어들이는 구조 이다.

1.Looping Dictionary With Values Instead of Keys

value 값으로 처음부터 looping 하는 방법이 있다.

values 함수는 dictionary의 value 들을 리턴해준다.

그러므로 values 함수를 다음 처럼 사용하면 for 반복구문에서 key 값 대신에 value 값들을 가지고 반복 로직을 실행 할 수 있다.

2.Looping Dictionary With Both Keys And Values

Key와 value 값 둘다 가지고 for 반복구문을 실행 하는 것도 가능하다.

items 함수를 사용하면 된다.
Dictionary의 items 함수는 key와 value를 tuple로 리턴해준다.
그러므로 다음처럼 for 반복구문에서 2개의 값을 동시에 받게 된다.

Assignment

Input으로 주어진 list의 각 요소(element)가 해당 list에 몇번 나타나는지 수를 dictionary로 만들어서 리턴해주세요. Dictionary의 key는 list의 요소 값이며 value는 해당 요소의 총 빈도수 입니다.

예를 들어, 다음과 같은 list가 input으로 주어졌다면:

my_list = ["one", 2, 3, 2, "one"]

다음과 같은 dictionary가 리턴되어야 합니다.

{
"one" : 2,
2 : 2,
3: 1
}

My solution

def get_occurrence_count(my_list):
  #이 함수를 구현 해주세요
  new_dict={}
 
  for i in my_list :
        if i not in new_dict:
            new_dict[i] = 1
        else:
            new_dict[i] += 1 
  return new_dict

Model solution

def get_occurrence_count(my_list):
  occurrence_count = { }
  #setdefault method를 사용해서 더 쉽고 간단하게 구현 할 수도 있지만
  #setdefault를 알아야만 할 수 있음으로 주석 처리 합니다.
  #for value in my_list:
  #occurrence_count[value] = occurrence_count.setdefault(value, 0) + 1
 
  for value in my_list:
    if value in occurrence_count:
      current_occurrence      = occurrence_count[value] 
      occurrence_count[value] = current_occurrence + 1
    else:
      occurrence_count[value] = 1
   
  return occurrence_count
profile
꾸준히!

0개의 댓글