Для начала вы извлекаете элемент из списка turn_list
, который является копией списка словарей turn_list = list(dictionary.keys())
, и извлечение элемента из этого списка не повлияет на исходный словарь.
Таким образом, вы захотите вставить ключ в сам исходный словарь, перебирая копию словаря, поскольку вы не можете обновить словарь, перебирая его
def draw_rows(dictionary):
#Take copy of the dictionary
dict_copy = dictionary.copy()
#Iterate over the copy
for key in dict_copy:
#If key is less than 1, pop that key-value pair from dict
if key < 1:
dictionary.pop(key)
#Print the dictionary
for key in dictionary:
print(key,": ", dictionary[key] * key, sep="")
def test_draw_rows():
print("1.")
draw_rows({2: 'f', 0: 'x', 4: 'z', -3: 'z'})
test_draw_rows()
Вы также можете упростить свой кодчерез понимание словаря, где вы создаете новый словарь с key > 1
def draw_rows(dictionary):
#Use dictionary comprehenstion to make a dictionary with keys > 1
dictionary = {key:value for key, value in dictionary.items() if key > 0}
#Print the dictionary
for key in dictionary:
print(key,": ", dictionary[key] * key, sep="")
def test_draw_rows():
print("1.")
draw_rows({2: 'f', 0: 'x', 4: 'z', -3: 'z'})
test_draw_rows()
Выходными данными в обоих случаях будет
1.
2: ff
4: zzzz
Если целью является только печать, мы можем выполнить итерациюи напечатайте только необходимые пары ключ-значение.
def draw_rows(dictionary):
#Iterate over dictionary
for key, value in dictionary.items():
#Print only those k-v pairs which satisfy condition
if not key < 1:
print(key,": ", value * key, sep="")
def test_draw_rows():
print("1.")
draw_rows({2: 'f', 0: 'x', 4: 'z', -3: 'z'})
test_draw_rows()