Issue
from datetime import datetime
dict_place = 1
birth_dict = {}
def date_key(date_string):
return datetime.strptime(date_string, "%d %b %Y")
while True:
name = input("Enter name of person: ")
birth_month = input("What month were they born?: ")
birth_day = input("What day of the month were they born?: ")
birth_year = input("what year were they born?: ")
birth_day = str(birth_day)
if len(birth_day) == 1:
birth_day = "0" + birth_day
birth_month = birth_month[0:3].capitalize()
birthdate = birth_day + " " + birth_month + " " + birth_year
birth_dict[dict_place] = {name: birthdate}
dict_place += 1
new_date = input(
"Do you want to enter another birthday?\n\nY for yes N for no\n\n"
)
if new_date.lower() == "y":
continue
else:
break
x = birth_dict.values()
print(x)
I'm new to python and trying to make something that sorts birthdays inputted by a user. I'm trying to turn the values of my dictionary into a list so I can sort it using datetime, but every time I do that it just returns the whole dictionary and not just the values.
I tried using the values function, but it doesn't seem to change anything.
Solution
You're creating a data structure like this:
{
1: {'Jon': '...'},
2: {'Jane': '...'},
...
}
This makes little sense. The keys 1
, 2
etc. you're painstakingly keeping track of with dict_place
have no meaning. If you just wanted this, you'd use a list instead, which implicitly keeps track of indices by itself. But beyond that, you don't even want this two-dimensional structure. You just want a simple dict with keys and plain values:
{
'Jon': '...',
'Jane': '...',
...
}
So change this:
birth_dict[dict_place] = {name: birthdate}
to:
birth_dict[name] = birthdate
And get rid of dict_place
, it's superfluous.
Answered By - deceze
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.