TULSI
TULSI

Reputation: 171

Adding new key value to existing dictionary in Python

i have created a dictionary in Python.

Employee = dict(EmpName="Peter", Empid="456", Designation="Country Head") 

now if i want to add to same dictionary something like this.

Employee.update(EmpName="Suresh", Empid="585", Designation="Director")

Please suggest. i am trying to add another element in same dictionary. but it is not getting added.

Upvotes: 0

Views: 1313

Answers (2)

BoarGules
BoarGules

Reputation: 16951

It seems to me you want a table of employees with 3 attribute columns, name, id, and designation. So your data has 2 dimensions, employees vs attributes. You can't do that with a single dictionary.

One way to do what I think you want is this. Start by defining the row structure with attributes.

>>> from collections import namedtuple
>>> Employee = namedtuple('Employee','EmpName,Empid,Designation')

Now build the employee dimension.

>>> employees = []
>>> employees.append(Employee(EmpName="Peter", Empid="456", Designation="Country Head"))
>>> employees.append(Employee(EmpName="Suresh", Empid="585", Designation="Director"))
>>> employees
[Employee(EmpName='Peter', Empid='456', Designation='Country Head'), Employee(EmpName='Suresh', Empid='585', Designation='Director')]

Although this is what I think you want, I have to point out that it is not a very useful data structure for further processing. For example, updates are difficult. Suppose Suresh gets promoted to Managing Director. The only way to update this data structure to reflect that is to search through all the employees to find the one you want to update. Or suppose an employee resigns: ditto.

Upvotes: 1

perror
perror

Reputation: 7426

You can simply do this:

Employee = dict(EmpName="Peter", Empid="456", Designation="Country Head")
...
Employee = dict(EmpName="Suresh", Empid="585", Designation="Director")

And, if you want to have an update() method, then create a class Employee which contains the update() method.

Anyway, as the fields seems to be fixed, I would advise you to use an object Employee with the fields EmpName, Empid and Designation in it.

One of the major benefit of using an object (in place of several dictionaries objects), is that you will be able to type (and, then, trust the content of each element) of a collection of Employee's objects. Where, manipulating a collection of dictionaries may just lead you to have missing fields or different labels for each fields.

Upvotes: 1

Related Questions