1. Sum Values
- sum up all the values in the dictionary
def sum_values(my_dictionary):
value_sum = 0
for value in my_dictionary.values():
value_sum += value
return value_sum
2. Even Keys
Next, we are going to do something similar, but we are going to use the keys in order to retrieve the values. Additionally, we are going to only look at every even key within the dictionary.
def sum_even_keys(my_dictionary):
total = 0
for key in my_dictionary.keys():
if key % 2 == 0:
total += my_dictionary.values(key)
return total
오류
TypeError: values() takes no arguments (1 given)
수정
def sum_even_keys(my_dictionary):
total = 0
for key in my_dictionary.keys():
if key % 2 == 0:
total += my_dictionary[key]
return total
3. Add Ten
modify the values within the dictionary, adding 10 to every value and returning modified dictionary
def add_ten(my_dictionary):
for key in my_dictionary.keys():
my_dictionary[key] = my_dictionary.values() + 10
return my_dictionary
오류
TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'
수정1
def add_ten(my_dictionary):
for key in my_dictionary.keys():
my_dictionary[key] = int(my_dictionary.values()) + 10
return my_dictionary
오류
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'dict_values'
수정 (해설지 참고)
def add_ten(my_dictionary):
for key in my_dictionary.keys():
my_dictionary[key] += 10
return my_dictionary
dictionary.values() 결과값 종류 / dictionary[key] 결과값 종류 알아보기
4. Values That Are Keys
making a program that will create a family tree
using a dictionary, return a list of all the children who are parents of other children
(values that hold values! - a nested dictionary(중첩 사전))
방법 1
def values_that_are_keys(my_dictionary):
keyvalues = []
for value in my_dictionary.values():
if value in my_dictionary.keys():
keyvalues.append(value)
return keyvalues
방법 2.
def values_that_are_keys(my_dictionary):
return [value for value in my_dictionary.values() if value in my_dictionary.keys()]
5. Largest Value
create a function that finds the maximum value in the dictionary and returns the associated key
def max_key(my_dictionary):
max_value = 0
for key in my_dictionary.keys():
if my_dictionary[key] >= max_value:
max_key = key
max_value = my_dictionary[key]
return max_key
다른 방법 (정답지)
def max_key(my_dictionary):
largest_key = float("-inf")
largest_value = float("-inf")
for key, value in my_dictionary.items():
if value > largest_value:
largest_value = value
largest_key = key
return largest_key
We start by using float("-inf") in order to initialize them to the lowest possible value. To retrieve the key and value at the same time, we use the items() function.
차이점 비교해보기
'개발일기 > PYTHON [codecademy]' 카테고리의 다른 글
Recap (Function Arguments) (0) | 2022.08.14 |
---|---|
[codecademy] 파이선 초보 단계 끝! (0) | 2022.08.13 |
[Beginner] Code Challenge: Classes (0) | 2022.08.13 |
[Beginner] Code Challenge: Dictionaries 2 (0) | 2022.08.13 |
[Beginner] Code Challenge: Strings (0) | 2022.08.13 |
댓글