Reputation: 33
I have added a employee class object inside a dictionary successfully .But i am not able to get back the value from the same dictionary? Below are the code and output.
source code:
# decalre a dict
employee_collection = {}
# Class object to store employee's details
class employee:
# Constructor
def __init__(self,name,age):
self.name = name
self.age = age
# Display the object values
def print_property(self):
print(f"name is {self.name} and age is {str(self.age)}")
# loop to add multiple employee details
for x in range(1, 6):
obj= employee("xxx", 28+x)
employee_collection.update({x : obj})
# extract the employee detail from and print the vaue to user
for x in employee_collection:
# print(x.name)
print(x)
print(employee_collection)
output :
1
2
3
4
5
{1: <__main__.employee object at 0x0327F610>, 2: <__main__.employee object at 0x03550C70>, 3: <__main__.employee object at 0x03550580>, 4: <__main__.employee object at 0x035503B8>, 5: <__main__.employee object at 0x03550FB8>}
My question is: How to print the name and age using loop in main method?
Upvotes: 3
Views: 3456
Reputation: 380
To iterate through a dictionary you can use its keys()
, values()
or items()
. Since you want both the key (x) and the value (employee) you want to use items()
which returns all dictionary key-value pairs as so-called tuple
in a list:
for x, employee in employee_collection.items():
print(f'Number: {x}, Name: {employee.name}, age: {employee.age}') # this is printing a format-string
Upvotes: 2
Reputation: 3555
Two methods. The dict is storing the instance of each employee
(which should be Employee
btw).
You can either print the properties of the instance, or change what happens when you try to print an object.
The former:
for key, e in employee_collection.items():
print(f'{x} {e.name} {e.age}')
The latter:
class Employee:
...
def __str__(self):
return f'{self.name} {self.age}'
for e in employee_collection.values():
print(e)
Upvotes: 2