Professional Documents
Culture Documents
Any
key of the dictionary is associated (or mapped) to a value. The
values of a dictionary can be any Python data type.
So dictionaries are unordered key-value-pairs. Python dictionary is
an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair.
While values can be of any data type and can repeat, keys must be of
immutable type (string, number or tuple with immutable elements)
and must be unique.
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
As you can see above, we can also create a dictionary using the built-
in function dict().
thisdict = {
"apple": "green",
"banana": "yellow",
"cherry": "red"
}
print(thisdict)
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Adding Items
Dictionary are mutable. We can add new items or change the value of
existing items using assignment operator.
If the key is already present, value gets updated, else a new key: value
pair is added to the dictionary.
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
thisdict["damson"] = "purple"
print(thisdict)
Removing Items
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
del(thisdict["banana"])
print(thisdict)
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
print(len(thisdict))
Python Dictionary Methods
Methods that are available with dictionary are tabulated below.
Some of them have already been used in the above examples.
Method Description
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
print(item)
list(sorted(marks.keys()))
output
('Math', 0)
('English', 0)
('Science', 0)
Questions
1. What is Dictionary?
2. Write the method by which we can declare a dictionary.
3. Can we modify a dictionary? Explain with an example.
4. What are dictionary keys?
5. What will be the output of the following Python code?
Dic = {1:10, 2:20, 3:30, 4:40, 5:50, }
print(Dic.items())
print(Dic.keys())
print(Dic.values()
6. Create dictionary called Employee containing Emp_id, Ename
and salary. Write a menu driven program to perform the
following:
a. Add Employee
b. Modify Employee
c. Delete Employee
d. Display detail in ascending order and
e. Exit
Anil Kumar
KV sec-5, Dwarka