#python #python-3.x #dictionary #return
#python #python-3.x #словарь #Возврат
Вопрос:
Например, у меня есть этот dict, и я хочу вернуть его n-е значение
d = {'Hello':4, 'World':17, 'Hi':2, 'Again':46}
Примечание: я знаю, что dicts неупорядочены, и мне все равно, я просто хочу вернуть все ключи один за другим.
В моей программе я просто хочу произвести вычисления со значениями, а ключи будут вводиться пользователем, поэтому мы не знаем ключей.
Как я могу вернуть n-е значение в этом dict следующим образом?
Вот полный код y-программы, ошибка находится во 2-й функции определения, в строке 23
#Subroutines
def dumptodaydate():
import pickle
with open('LastOpenDate.txt', 'wb') as DOT:
import time
ODate = time.strftime('%d')
OMonth = time.strftime('%m')
OYear = time.strftime('%Y')
List = {'Day':ODay, 'Month':OMonth, 'Year':OYear}
pickle.dump(List, DOT)
def caltimelefttask():
import pickle
with open('LastOpenDate.txt', 'rb') as LOD:
List = pickle.load(LOD)
from datetime import date
Today = date.today()
ODay = List['Day']
OMonth = List['Month']
OYear = List['Year']
DifDay = (Today(eval(OYear),eval(OMonth), eval(ODay)).days
for key in Lesson:
OTimetask = Lesson[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating 50
Lesson[key]['Rating'] = Rating
for key in Exercises.keys():
OTimetask = Exercises[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating 50
Exercises[key]['Rating'] = Rating
for key in Assignment.keys():
OTimetask = Assignment[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating 50
Assignment[key]['Rating'] = Rating
def loadtxt():
import pickle
with open('LessonOut.txt', 'rb') as Li:
Lesson = pickle.load(Li)
with open('ExercisesOut.txt', 'rb') as Ei:
Exercises = pickle.load(Ei)
with open('AssignmentOut.txt', 'rb') as Ai:
Assignment = pickle.load(Ai)
def ADD():
print('Name of task? (Keep it short for convenience Example: Math1)n(Must be diferent from any other non deleted tasks)')
Name = input('>>>')
print('Description of task? (this can be as long as you want)')
Desc = input('>>>')
print('Rate the time it takes you to do the task on a scale from 1 to 20')
Time = input('>>>')
print('Rate the importance of the task on a scale from 1 to 20')
Imp = input('>>>')
print('Rate how much you want to do it on a scale from 1 to 5 n(1= want to do it, 5= don't want to')
Want = input('>>>')
print('enter deadline (day)')
TimeDay = input('>>>')
print('enter deadline (month)')
TimeMonth = input('>>>')
print('enter deadline(year)')
TimeYear = input('>>>')
print('what type of homework is it? (Lesson/Exercises/Assignment)')
TaskType = input('>>>')
from datetime import date
Today = date.today()
TaskForDate = date(eval(TimeYear), eval(TimeMonth), eval(TimeDay))
TimeLeftTemp = abs((TaskForDate - Today).days)
print ('You have', TimeLeftTemp, 'days to finish this task.')
Rating = eval(Time) eval(Imp) eval(Want) - (TimeLeftTemp * 2)
if TimeLeftTemp < 4:
Rating = Rating 50
if TimeLeftTemp <= 0:
Rating = Rating 50
if TaskType == 'Lesson':
Lesson[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Exercises':
Exercises[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Assignment':
Assignment[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
def DEL():
print ('What type of task is it? nLesson, Exercises or Assignment)')
WhatDict = input('>>>')
if WhatDict == Lesson:
print(Lesson.keys())
if WhatDict == Exercises:
print(Exercises.keys())
if WhatDict == Assignment:
print(Assignment.keys())
print ('What task do you want do delete?')
WhatDel = input('>>>')
if WhatDict == 'Lesson':
try:
del Lesson[WhatDel]
except:
pass
elif WhatDict == 'Exercises':
try:
del Exercises[WhatDel]
except:
pass
elif WhatDict == 'Assignment':
try:
del Assignment[WhatDel]
except:
pass
pass
else:
print('Sorry, the type of task is not recognised, please try again.')
def sort_by_subdict(dictionary, subdict_key):
return sorted(dictionary.items(), key=lambda k_v: k_v[1][subdict_key])
def SHOW():
ShowWhat = input('What type of task do you want to do?nLesson/Exercises/Assignment)n>>>')
if ShowWhat == 'Lesson' or 'lesson':
print (sort_by_subdict(Lesson, 'Rating'))
elif ShowWhat == 'Exercises' or 'exercises':
print (sort_by_subdict(Exercises, 'Rating'))
elif ShowWhat == 'Assignment' or 'assignment':
print (sort_by_subdict(Assignment, 'Rating'))
else:
print('Type of task not recognosed, please try again')
def dumptxt():
import pickle
with open('LessonOut.txt', 'wb') as Lo:
pickle.dump(Lesson, Lo)
with open('ExercisesOut.txt', 'wb') as Eo:
pickle.dump(Exercises, Eo)
with open('AssignmentOut.txt', 'wb') as Ao:
pickle.dump(Assignment, Ao)
loadtxt()
while True:
print ('WARNING NEVER EXIT PROGRAM WITHOUT USING THE quit COMMAND,nOR ALL ACTIONS DONE WILL BE LOST')
print ('Commands:')
print ('add (to add a task)')
print ('del (to delete a task)')
print ('quit (to exit program)')
print ('show (to see your tasks)')
Input = input('>>>')
if Input == 'add':
ADD()
elif Input == 'del':
DEL()
elif Input == 'show':
SHOW()
elif Input == 'quit':
print ('are you sure you want to quit? y/n')
Input = input('>>>')
if Input == 'y':
dumptxt()
quit()
elif Input == 'n':
print ('Not exiting')
else:
print ('Error, command not recognised')
Это выдает синтаксическую ошибку:
for key in Lesson:
#syntax error ^
# here
Комментарии:
1. Вы хотя бы кратко рассматривали возможность чтения документации ?
Ответ №1:
Вы можете просто перечислить все ключи в dict напрямую, используя for key in d
:
for key in d:
if d[key] < 20:
d[key] -= 4
else:
d[key] = 4
Комментарии:
1. Выдает синтаксическую ошибку. Забыл сказать, что я был на python 3.4, в этом, должно быть, проблема.
2. @TheD0ubleT Что такое
SyntaxError
? Этот код отлично работает для меня.3. для ключа в уроке «Ошибка здесь»: делать вещи
4. @TheD0ubleT Можете ли вы отредактировать свой вопрос, чтобы включить полный пример, который воспроизводит проблему? Потому что, если
Lesson
это dict ,for key in Lesson:
должно работать нормально, независимо от того, какую версию вы используете.5. @TheD0ubleT: вам нужно привести пример, который я могу скопировать / вставить, чтобы воспроизвести ошибку. То, что вы вставили, отлично работает, если я скажу
Lesson = {"a" : 1, "b": 2}
and thenfor key in Lesson: print(key)
.