Dictionary
Dictionary
The keys in the dictionary are Boolean, integer, floating point number,
and string data types, which are all acceptable.
If you try to create a key which is of a mutable type you'll get an error - specifically
the error will be a TypeError. In the example above, I tried to create a key which
was of list type (a mutable data type).
When it comes to values inside a Python dictionary there are no restrictions. Values
can be of any data type - that is they can be both of mutable and immutable types.
Note: Another thing to note about the differences between keys and values in
Python dictionaries, is the fact that keys are unique. This means that a key can only
appear once in the dict1ionary, whereas there can be duplicate values.
Note – Dictionary keys are case sensitive, the same name but different cases
of Key will be treated distinctly.
Creating a dictionary
The dictionary can be created by using multiple key-value pairs enclosed with the
curly brackets { }, and each key is separated from its value by the colon (:).
To create an empty dict1ionary, first create a variable name which will be the name
of the dict1ionary.
Then, assign the variable to an empty set of curly braces, {}.
dictionary_name is the variable name. This is the name the dict1ionary will have.
= is the assignment operator that assigns the key:value pair to
the dict1ionary_name.
Example 1:
dict1={ }
print(dict1)
Output:
{}
Example 2:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(dict1)
Output:
{'sname': 'abc', 'age': 25, 'mks': 80, 'course': 'BCA'}
Type()
Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(type(dict1))
Output:
<class 'dict1'>
Dictionaries cannot have two items with the same key. Although it will not
display any error for repeated key but new value of key will override previous
value.
Example:
dict1={"sname":"abc","age":25,"age":80, "course":"BCA"}
print(dict1)
Output:
{'sname': 'abc', 'age': 80, 'course': 'BCA'}
Dictionary Length
To determine how many items a dictionary has, use the len() function.
Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(len(dict1))
Output:
4
dict1={"car":"Hyundai","foglight":"True","model":80, "model":
["i10","venue","creta"]}
print((dict1))
Output:
{'car': 'Hyundai', 'foglight': 'True', 'model': ['i10', 'venue', 'creta']}
Example:
dict1={"car":"Hyundai","foglight":"True","start_amt":500000, "model":
["i10","venue","creta"]}
print((dict1["car"]))
print((dict1["foglight"]))
print((dict1["start_amt"]))
print((dict1["model"]))
Output:
Hyundai
True
500000
['i10', 'venue', 'creta']
Note: dict1[“model”][1] : will display “venue”
Example 2:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
for a in dict1:
print(a)
Output:
sname
age
mks
course
keys()
Output:
dict1_keys(['sname', 'age', 'mks', 'course'])
values()
This method is used to find all the values of dictionary
Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(dict1.values())
Output:
dict1_values(['abc', 25, 80, 'BCA'])
items()
The items() method will return each item in a dictionary, as tuples in a list.
Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(dict1.items())
Output:
dict1_items([('sname', 'abc'), ('age', 25), ('mks', 80), ('course', 'BCA')])
Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
if "age" in dict1:
print("Key exist!!")
else:
print("Key doesn't exist")
Output:
Key exist!!
Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(dict1)
dict1["univ"]="GGSIPU"
print(dict1)
Output:
{'sname': 'abc', 'age': 25, 'mks': 80, 'course': 'BCA'}
{'sname': 'abc', 'age': 25, 'mks': 80, 'course': 'BCA', 'univ': 'GGSIPU'}
Update dictionary
The update() method will update the dictionary with the items from the given
argument.
Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(dict1)
dict1.update({"age":32})
print(dict1)
Output:
{'sname': 'abc', 'age': 25, 'mks': 80, 'course': 'BCA'}
{'sname': 'abc', 'age': 32, 'mks': 80, 'course': 'BCA'}
Pop()
Popitem()
This method is used to remove last item from the dictionary. We can access the
popped out element by saving it into some variable.
Example 1:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
out=dict1.popitem()
print("Popped out element= ",out)
print("Remaining dictionary= ",dict1)
Output:
Popped out element= ('course', 'BCA')
Remaining dictionary= {'sname': 'abc', 'age': 25, 'mks': 80}
del()
This method is used to delete a particular element from dictionary. It can also be
used to delete complete dictionary.
Example 1:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
del dict1["age"]
print(dict1)
Output:
{'sname': 'abc', 'mks': 80, 'course': 'BCA'}
Example 2:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
del dict1
print(dict1)
Output:
Error
clear()
Clear method delete all the elements of the dictionary.
Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
dict1.clear()
print(dict1)
Output:
{}
Copy()
Output:
{'sname': 'abc', 'age': 25, 'mks': 80, 'course': 'BCA'}
{'sname': 'abc', 'age': 25, 'mks': 80, 'course': 'BCA'}
Nested Dictionary
One dictionary can be a part of another dictionary. This concept is called as
nested dictionary.
bca_class = {
"student1" :
{ "name" : "Sneha",
"mks" : 25
},
"student2" :
{ "name" : "Amit",
"mks" : 40
},
"student3" :
{ "name" : "Kavita",
"mks" : 30
},
"student4" :
{ "name" : "Ravi",
"mks" : 37
}
}
print(bca_class)
OR
print(bca_class["student1"])
print(bca_class["student2"])
print(bca_class["student3"])
print(bca_class["student4"])
Output:
{'student1': {'name': 'Sneha', 'mks': 25}, 'student2': {'name': 'Amit', 'mks': 40},
'student3': {'name': 'Kavita', 'mks': 30}, 'student4': {'name': 'Ravi', 'mks': 37}}
OR
{'name': 'Sneha', 'mks': 25}
{'name': 'Amit', 'mks': 40}
{'name': 'Kavita', 'mks': 30}
{'name': 'Ravi', 'mks': 37}
Q1 Input values from user and create a dictionary.
d={}
d["ename"]=input("Enter employee name: ")
d["age"]=int(input("Enter age: "))
d["salary"]=int(input("Enter salary: "))
d["desig"]=input("Enter designation: ")
print(d)
Q2. Write a Python script to generate and print a dictionary that contains
a number (between 1 and n) in the form (x, x*x).
n=int(input("Input a number "))
d = dict() #OR d={ }
for x in range(1,n+1):
d[x]=x*x
print(d)
Q3 Write a program to find whether a particular key exist in the dictionary
or not.
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
ky=input("Enter the key you want to search: ")
if ky in dict1:
print("Key exists!!")
else:
print("Key does not exist!!")
Q4 Replace dictionary values from one dictionary to another, in case key
matches.
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
dict2={"ename":"abc","age":50,"mks":80, "course":"BBA"}
dict3=dict1.copy()
for key in dict1:
if key in dict2:
dict1[key] = dict2[key]
print("The original dictionary: " + str(dict3))
print("The updated dictionary: " + str(dict1))
Q5 Create a nested dictionary for 5 employees of an organization.
bca_class = {
"student1" : {
"name" : "Sneha",
"mks" : 25
},
"student2" : {
"name" : "Amit",
"mks" : 40
},
"student3" : {
"name" : "Kavita",
"mks" : 30
},
"student4" : {
"name" : "Ravi",
"mks" : 37
}
}
print(bca_class)