[go: up one dir, main page]

0% found this document useful (0 votes)
13 views7 pages

Dictionary

notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views7 pages

Dictionary

notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Dictionary

A dictionary in Python is made up of key-value pairs. It is the mutable data-


structure. The dictionary is defined into element Keys and values.
Note: the keys are the immutable Python object
The first way is by using a set of curly braces, { }, and the second way is
by using the built-in dict() function.

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, {}.

The general syntax for this is the following:

dictionary_name = {key: value}

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()

We can find the type of object by using type keyword.

Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(type(dict1))

Output:
<class 'dict1'>

Dealing with duplicate keys

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

Heterogeneous type of data in dictionary

We can save multiple type of data in a dictionary.


Example:

dict1={"car":"Hyundai","foglight":"True","model":80, "model":
["i10","venue","creta"]}
print((dict1))

Output:
{'car': 'Hyundai', 'foglight': 'True', 'model': ['i10', 'venue', 'creta']}

To print individual values of dictionary


We can also print individual elements of a dictionary with the help of keys.

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()

This method is used to access all the keys from dictionary.


Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(dict1.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')])

Check if Key Exists


The keyword “in” is used to find whether a particular key exists in dictionary or not.

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!!

Add values in dictionary


We can add a new element in the dictionary by just specifying dictionary name, key
and its value.

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'}

Change values in dictionary

We can change value of any particular key in the dictionary.


Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
print(dict1)
dict1["course"]="B.Tech"
print(dict1)
Output:
{'sname': 'abc', 'age': 25, 'mks': 80, 'course': 'BCA'}
{'sname': 'abc', 'age': 25, 'mks': 80, 'course': 'B.Tech'}

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'}

Note: dict1.update({“status”:”pass”}) will add 1 more element in the dictionary as


status key does not already exist.

Pop()

We can remove a particular element from dictionary using pop() method.


dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
dict1.pop("sname")
print(dict1)
Output:
{'age': 25, 'mks': 80, 'course': 'BCA'}

Note: dict1.pop() will display error

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()

This method is used to copy one dictionary into another.


Example:
dict1={"sname":"abc","age":25,"mks":80, "course":"BCA"}
new_dict1=dict1.copy()
print(dict1)
print(new_dict1)

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)

You might also like