Reputation: 1
I am trying to order a list user data, in the form of dictionaries, which contains random user data generated by an API. I am using .get to pull the date of birth (dob) from the dictionaries within the list to organize the data, but I keep getting the error "AttributeError: 'randomuser' object has no attribute 'get'". Since it seems that the problem is coming from the interaction with the 'randomuser' class, I tried side-stepping the class by placing the user data directing into a user dictionary in the main program loop, and this seemed to work. But as I am trying to learn OOP, any help in explaining where I am going wrong with the 'randomuser' class is appreciated! Cheers!
import requests
import json
class randomuser(object):
def __init__(self, firstname, lastname, gender, username, password, dob) -> None:
self.firstname = firstname
self.lastname = lastname
self.gender = gender
self.username = username
self.password = password
self.dob = dob
self.user_dict = {
"firstname": self.firstname,
"lastname": self.lastname,
"gender": self.gender,
"username": self.username,
"password": self.password,
"dob": self.dob
}
def __repr__(self):
return str(self.user_dict)
"""
create a 10 user list with 5 men and 5 women
"""
male = 0
female = 0
user_list = []
while male < 5 or female < 5:
response = requests.get("https://randomuser.me/api/") # pulls JSON object from API
user = json.loads(response.text)['results'][0] # converst to Python dictionary
firstname = user['name']["first"]
lastname = user['name']["last"]
gender = user['gender']
username = user['login']['username']
password = user['login']['password']
dob = user['dob']['date']
new_user = randomuser(firstname, lastname, gender, username, password, dob)
if gender == 'male' and male < 5:
male += 1
user_list.append(new_user)
elif gender == 'female' and female < 5:
female += 1
user_list.append(new_user)
"""
sort user list by DOB
"""
user_list.sort(key=lambda x: x.get('dob'))
print(user_list)
Upvotes: 0
Views: 653
Reputation: 191733
You have a list of classes, not dictionaries, so your lambda argument is a class without a get
function
To sort by dob
attribute, you'd do this
user_list.sort(key=lambda x: x.dob)
I'd also suggest using dataclasses
or a NamedTuple
rather than define user_dict
, as you're only using this for printing
Upvotes: 1