What are the advantages and disadvantages of membrane structures.pptx
Python dictionaries
1. PYTHON APPLICATION PROGRAMMING -
18EC646
Module 3
DICTIONARY
Prof. Krishnananda L
Department of ECE
Govt SKSJTI
Bengaluru
2. Python Dictionary
in python is an unordered/ordered collection of data values, which
are mutable.
Created using curly braces; elements are comma separated values
Dictionary is a python object with data type <‘dict’>
More generally known as Associative array
Python Dictionary is used to store the data in a key-value pair format. Associates
a ‘key’ with a value
Dictionary is a collection of key-value pairs where the value can be any Python
object (ex: list, tuple, integer, string etc). In contrast, the keys must be immutable
Python object, i.e., Numbers, string, or tuple
Dictionaries store a mapping between a set of keys and a set of values.
: D={“LK”: “Python”, “Branch” : “ECE”}.
2
3. 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 (:)
Values in a dictionary can be of any data type and can be duplicated, whereas
keys can’t be repeated and must be immutable.
Dictionary Keys are “case sensitive” and unique
Dictionary can also be created by the built in function . An empty
dictionary can be created by just placing two curly braces .
thisdict = {
"brand": "Suzuki",
"model": "Swift",
"year": 2020
}
print(thisdict)
Output:
{'brand': 'Suzuki', 'model': 'Swift', 'year': 2020}
employee= { "Name":"Abhishek",
"Designation":"System Engineer", "Salary": 40000,
"Company":"Microsoft"
}
print ("Employee details")
print (employee)
Output:
Employee details
{'Name': 'Abhishek', 'Designation': 'System Engineer',
'Salary': 40000, 'Company': 'Microsoft'}
3
4. # Creating a Dictionary
# with Integer Keys
Dict = {1: "Digital communication", 2: "Embedded System", 3: "Microwave and
Antennas",4:"Python"}
print("Dictionary with the use of Integer Keys:n ")
print(Dict)
print(type(Dict))
Output:
Dictionary with the use of Integer Keys:
{1: 'Digital communication', 2: 'Embedded System', 3: 'Microwave and Antennas', 4: 'Python'}
<class 'dict'>
# with Mixed keys
Dict = {"A":1,"B":2,3.14:"Pi"}
print("Dictionary with the use of Mixed Keys:n ")
print(Dict)
Output:
Dictionary with the use of Mixed Keys:
{'A': 1, 'B': 2, 3.14: 'Pi'}
## string keys and different data types for values
>>>d1={"Shape":"circle","color":["red",”blue"],"size":4}
>>> print (d1)
{'Shape': 'circle', 'color': ['red', 'blue'], 'size': 4}
## integer keys and values of different data type
>>> d2={1:"hello", 2:(34,56), 3:[23.45, 67,88], 4:True}
>>> print (d2)
{1: 'hello', 2: (34, 56), 3: [23.45, 67, 88], 4: True}
4
Note: We can define, modify, view, lookup, and delete
the key-value pairs in the dictionary
5. # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ", Dict)
Output:
Empty Dictionary: {}
# Creating a Dictionary with dict() method
Dict = dict({1: "India", 2: "America", 3:"China"})
print("Dictionary with the use of dict(): ",Dict)
Output:
Dictionary with the use of dict(): {1: 'India', 2: 'America', 3: 'China'}
# Creating a Dictionary with each item as a Pair
Dict = dict([(1, "India"), (2, "America"), (3,"China")])
print("nDictionary with each item as a pair: ")
print(Dict)
Output:
Dictionary with each item as a pair:
{1: 'India', 2: 'America', 3: 'China'}
### illustrating mutability
>>> d2={1:"hello", 2:(34,56), 3:[23.45, 67,88], 4:True}
>>> d2[1]='welcome‘ ## change value at key 1
>>> print (d2)
{1: 'welcome', 2: (34, 56), 3: [23.45, 67, 88], 4: True}
## value can be duplicated i.e., more keys can have same value
>>> d2={1:"hello", 2:(34,56), 3:[23.45, 67,88], 4:True}
>>> d2[2]='hello'
>>> print (d2)
{1: 'hello', 2: 'hello', 3: [23.45, 67, 88], 4: True}
5
6. Accessing elements from a Dictionary
# Creating a Dictionary
Dict = {'Name': 'Abhi', 'USN': '1SK18EC001', 'class':
'ECE', 6 : 'Sem'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['Name'])
print(Dict['USN'])
# accessing a element using key
print("Accessing a element using key:")
print(Dict.[6])
# accessing a element using get method
print("Accessing a element using get:")
print(Dict.get('class'))
In order to access the items of a dictionary, refer to its key name. Key can be used inside square
brackets.
There is method that will also help in accessing the element from a dictionary
Output:
Accessing a element using key:
Abhi
1SK18EC001
Accessing a element using key:
Sem
Accessing a element using get:
ECE
6
7. #### employee data
Employee ={
"Name": “Manasa", "salary":50000,
"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
## accessing value using Key
print("Name : %s" %Employee["Name"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output:
<class 'dict'>
printing Employee data ....
Name : Manasa
Salary : 50000
Company : GOOGLE 7
>>> d = {'user':'krishna', 'pwd':1234}
>>> d['user'] ## access value using key
'krishna'
>>> d['pwd']
1234
>>> d['krishna'] ## invalid access
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
d['krishna']
KeyError: 'krishna‘
>>> d['id']=25 ## appending new key-value pair
>>> print (d)
{'user': 'krishna', 'pwd': 1234, 'id': 25}
>>> d['salary']=50000
>>> print (d)
{'user': 'krishna', 'pwd': 1234, 'id': 25, 'salary': 50000}
>>> d['user']='anusha‘ ## changing value using key
>>> print (d)
{'user': 'anusha', 'pwd': 1234, 'id': 25, 'salary': 50000}
11. Adding elements to a Dictionary
In Python Dictionary, new elements can be inserted in multiple ways.
One value at a time can be added to a Dictionary by defining value along with the key: Ex:
Dict[key]= ‘value’
Updating an existing value in a Dictionary can be done by using the built-in method.
Nested key values can also be added to an existing
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'Abhi'
Dict[1] = 'Vinay'
Dict[2] = 'Govind'
Dict[3] = ‘Akshata’
print("nDictionary after adding 4 elements: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 4 elements:
{0: 'Abhi', 1: 'Vinay', 2: 'Govind', 3: 'Akshata'}
11
12. # Adding set of values to a single Key
car= {"brand":"Marutisuzuki", "model":"Swift",
"year": 2020 }
print("original dictionary elements")
print (car)
car['price']=50000,60000
print (car)
# Adding (appending) to the existing dictionary
>>> d2={1:"hello", 2:(34,56), 3:[23.45, 67,88], 4:True}
>>> d2[5]=35 ## key 5 is added at the end
>>> print (d2)
{1: 'hello', 2: (34, 56), 3: [23.45, 67, 88], 4: True, 5: 35}
# Updating existing Key's Value
Dict[0]=45
Dict[1]=67
print ("after updating values")
print (Dict)
Output:
after updating values
{0: 45, 1: 67, 2: 'Govind', 3: 'Akshata'}
12
# Adding Nested Key value to Dictionary
Dict[4]={'Nested':{'abhi':‘python', 'vinay':‘HDL',
'Govind':‘datascience'}}
print("nAdding a Nested Key: ")
print(Dict)
Output:
Adding a Nested Key:
{0: 'Abhishek', 1: 'Vinay', 2: 'Govind', 3: ‘Akshata’,
4: {'Nested': {'abhi': 'python', 'vinay': ‘HDL',
'Govind': ‘datascience'}}}
Output:
{'brand': 'Marutisuzuki', 'model': 'Swift', 'year': 2020, 'price': (50000, 60000)}
13. #### employee data
### illustrating user input to update the existing
values
Employee ={"Name": "Manasa",
"salary":50000,"Company":"GOOGLE"}
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["salary"] = int(input("Salary: "));
Employee["Company"]= input("Company:");
print("printing the new data");
print(Employee)
Output:
printing Employee data ....
Name : Manasa
Salary : 50000
Company : GOOGLE
Enter the details of the new employee....
Name: Sahana
Salary: 40000
Company:Wipro
printing the new data
{'Name': 'Sahana', 'salary': 40000, 'Company': 'Wipro'}
13
# Adding (appending) key-vlaue pair
car = {"brand":"Marutisuzuki", "model":"Swift",
"year": 2020 }
print("original dictionary elements")
print (car)
print ("dictionary after appending")
car['color']='red'
print (car)
Output:
dictionary after appending
{'brand': 'Marutisuzuki', 'model': 'Swift', 'year': 2020, 'color': 'red'}
14. Accessing element of a nested dictionary
Dict = {'LK': {'food': 'Ice Cream'},
'Arun': {'food': 'dessert'},
'Rahul':{'food': 'Noodles'}
}
# Accessing element using key and [ ]
print("details of LK:")
print(Dict['LK'])
print (" LK likes:")
print(Dict['LK']['food'])
print (" Arun likes:")
print(Dict['Arun']['food'])
print (" Rahul likes:")
print(Dict['Rahul']['food'])
Output:
details of LK:
{'food': 'Ice Cream'}
LK likes:
Ice Cream
Arun likes:
dessert
Rahul likes:
Noodles
14
15. in operator & Looping in Dictionary
##To check whether ‘key’is present in a dictionary,
#We use ‘in’operator
cardict = {
"brand": "Maruti",
"model": "Celerio",
"year": 2015
}
if "model" in cardict:
print("Yes, 'model' is one of the keys in the
dictionary")
else:
print ("No, 'model' is not a key in this dictionary")
Output:
Yes, 'model' is one of the keys in the dictionary
When looping through a dictionary, the return value are
the keys of the dictionary, by default
cardict = {
"brand": "Maruti",
"model": "Celerio",
"year": 2015
}
for x in cardict:
print (x)
Output:
brand
model
year
### Print all key names in the
dictionary, one by one:
### Print all values in the dictionary, one by one:
cardict = {
"brand": "Maruti",
"model": "Celerio",
"year": 2015
}
for x in cardict:
print (cardict[x])
Output:
Maruti
Celerio
2015
15
16. Copying Dictionaries
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
One way is to use the built-in Dictionary method copy()
Another method is to make a copy of a dictionary with the dict() function
## copying dictionary
car= {"brand":"Marutisuzuki",
"model":"Swift",
"year": 2020
}
print("original dictionary ")
print (car)
mycar=car.copy() ## using method
print ("copied using copy() method")
print (mycar)
print ("copied using dict() function")
yourcar=dict(car) ## using function
print (yourcar)
Output:
original dictionary
{'brand': 'Marutisuzuki', 'model': 'Swift', 'year':
2020}
copied using copy() method
{'brand': 'Marutisuzuki', 'model': 'Swift', 'year':
2020}
copied using dict() function
{'brand': 'Marutisuzuki', 'model': 'Swift', 'year':
2020}
>>> mycar==yourcar
True
>>> mycar is yourcar
False
16
17. Dictionary Methods
1. copy ()- They copy() method returns a copy of the dictionary.
2. clear()-The clear() method removes all items from the dictionary.
3. keys () – returns a list containing keys of the dictionary
4. values()- returns a list of all values of the dictionary
5. items() – returns all key-value pairs of dictionary as tuple
6. fromkeys()- Returns a new dictionary with the specified key and value
7.update() – updates the dictionary using the given key-value pair. The argument
must be a dictionary, or an iterable object with key:value pairs.
8. setdefault()- Returns the value of specified key. If key does not exist, insert the
key with the specified value
9. get() – returns the value of a given key
10. pop () - Removes and returns an element from a dictionary having the given
key.
11.popitem()- Removes the last inserted key-value pair from the dictionary and
returns it as tuple.
17
18. Removing Elements from Dictionary
1) using keyword
In Python Dictionary, deletion of keys can be done by using the del
keyword. Using del keyword, specific values from a dictionary as well as whole
dictionary can be deleted. Items in a Nested dictionary can also be deleted by
providing specific nested key
will delete the entire dictionary
2) Using pop() method – deletes the value of the key specified
3) Using popitem() method- removes an arbitrary element/last element
4) Using clear() method- deletes all the elements of the dictionary
18
19. Contd..
## Illustration of Item deletion from dictionary
## using del keyword
subject={1:"Python", 2:"Java", 3:"OpenCV", 4:"Ruby"}
print("id of dictionary is ", id(subject))
print("size of dictionary is:", len(subject))
print ("original items in dictionary are")
print(subject)
print ("deleting some items using del")
del subject[2]
print ("dictionary after deleting one item")
print (subject)
print("id of modified dictionary is ", id(subject))
print("size of modified dictionary is:", len(subject))
print ("deleting entire dictionary")
del (subject)
print ("after deleting dictionary if we try to access, we
get")
print (subject)
Output:
id of dictionary is 67065768
size of dictionary is: 4
original items in dictionary are
{1: 'Python', 2: 'Java', 3: 'OpenCV', 4: 'Ruby'}
deleting some items using del
dictionary after deleting one item
{1: 'Python', 3: 'OpenCV', 4: 'Ruby'}
id of modified dictionary is 67065768
size of modified dictionary is: 3
deleting entire dictionary
after deleting dictionary if we try to access, we get
Traceback (most recent call last):
File "D:/18EC646/LK-MODULE 3/dictdel.py", line 17,
in <module>
print (subject)
NameError: name 'subject' is not defined
19
20. Contd..
## Illustration of Item deletion from dictionary
## using pop() method
## takes key as argument
subject={1:"Python", 2:"Java", 3:"OpenCV",
4:"Ruby"}
print("id of dictionary is ", id(subject))
print("size of dictionary is:", len(subject))
print ("original items in dictionary are")
print(subject)
print ("removing item using pop() method")
subject.pop(3)
print ("dictionary after removing item")
print (subject)
Output:
id of dictionary is 55982272
size of dictionary is: 4
original items in dictionary are
{1: 'Python', 2: 'Java', 3: 'OpenCV', 4: 'Ruby'}
removing item using pop() method
dictionary after removing one item
{1: 'Python', 2: 'Java', 4: 'Ruby'}
20
Note: with pop() method, one value with
the given key is removed from the
dictionary
21. Contd..
## Illustration of Item deletion from dictionary
## using popitem() method
## takes no argument
## removes the last item
subject={1:"Python", 2:"Java", 3:"OpenCV",
4:"Ruby"}
print("id of dictionary is ", id(subject))
print("size of dictionary is:", len(subject))
print ("original items in dictionary are")
print(subject)
print ("removing item using popitem() method")
subject.popitem()
print ("dictionary after removing one item")
print (subject)
Output:
id of dictionary is 57296848
size of dictionary is: 4
original items in dictionary are
{1: 'Python', 2: 'Java', 3: 'OpenCV', 4:
'Ruby'}
removing item using popitem() method
dictionary after removing one item
{1: 'Python', 2: 'Java', 3: 'OpenCV'}
21
Note: popitem() removes the last element
22. Contd..
## Illustration of Item deletion from dictionary
## using clear() method
subject={1:"Python", 2:"Java", 3:"OpenCV", 4:"Ruby"}
print("id of dictionary is ", id(subject))
print("size of dictionary is:", len(subject))
print ("original items in dictionary are")
print(subject)
print (" deleting using clear() method")
print ("deletes all items and returns empty dictionary")
subject.clear()
print ("dictionary after deleting")
print (subject)
Output:
id of dictionary is 60905384
size of dictionary is: 4
original items in dictionary are
{1: 'Python', 2: 'Java', 3: 'OpenCV', 4: 'Ruby'}
deleting using clear() method
deletes all items and returns empty dictionary
dictionary after deleting
{} 22
23. Dictionary Methods example
## illustration of different Dictionary methods
employee= {"Name":"Harsh", "Salary": 40000,
"Dept":"R&D", "company":"Accenture"}
print ("employee details are:")
print (employee)
print ("accessing element using get() method")
a=employee.get("Name")
print ("employee name is: ", a)
print ("getting all the keys using keys() method")
b=employee.keys()
print (b)
print ("getting all the values using values() method")
c=employee.values()
print (c)
print ("getting all key-value pairs using items() method")
d=employee.items()
print (d)
print("adding an element using update() method")
employee.update({"Location": "Bangalore"})
print("Dictionary after updation is:")
Output:
employee details are:
{'Name': 'Harsh', 'Salary': 40000, 'Dept': 'R&D', 'company':
'Accenture'}
accessing element using get() method
employee name is: Harsh
getting all the keys using keys() method
dict_keys(['Name', 'Salary', 'Dept', 'company'])
getting all the values using values() method
dict_values(['Harsh', 40000, 'R&D', 'Accenture'])
getting all key-value pairs using items() method
dict_items([('Name', 'Harsh'), ('Salary', 40000), ('Dept', 'R&D')
('company', 'Accenture')])
addingan element usingupdate() method
Dictionary after updation is:
{'Name': 'Harsh', 'Salary': 40000, 'Dept': 'R&D', 'company':
'Accenture', 'Location': 'Bangalore'}
23
24. Contd..
### using methods to print dictionary details
employee= {"Name":"Harsh", "Salary": 40000, "Dept":"R&D",
"company":"Accenture"}
print ("employee details are:")
print (employee)
## keys() method to return the keys of a dictionary:
print ("keys of the dictionary are:")
for x in employee.keys():
print(x)
### values() method to return values of a dictionary:
print ("values of the dictionary are:")
for x in employee.values():
print(x)
##Loop through both keys and values, by using the items()
method:
print ("keys and values of the dictionary are:")
for x, y in employee.items():
print(x, y)
Output:
employee details are:
{'Name': 'Harsh', 'Salary': 40000, 'Dept': 'R&D',
'company': 'Accenture'}
keys of the dictionary are:
Name
Salary
Dept
company
values of the dictionary are:
Harsh
40000
R&D
Accenture
keys and values of the dictionary are:
Name Harsh
Salary 40000
Dept R&D
companyAccenture
24
25. Strings Lists Tuples Dictionaries Sets
Immutable, ordered Mutable, ordered Immutable, ordered Mutable Mutable, unordered
Slicing can be done Slicing can be done Slicing can be done Slicing can’t be done Slicing can’t be done
Duplicates allowed Duplicates allowed Duplicates allowed Duplicate keys not
allowed
Duplicates NOT
allowed
They are enclosed in
single, double or triple
quotes
They are enclosed in
square braces [ ]
They are enclosed in
parenthesis ( )
They are enclosed in
curly braces { }
They are enclosed in
curly braces { }
Elements can be
numbers, tuples,
alphabets etc, all
treated as set of
characters
Elements can be
numbers, strings,
tuples etc
Elements can be
numbers, strings, lists
etc
Keys must be
immutable objects.
Values can be of any
type
Elements can be
numbers, strings, lists,
tuples etc
Elements are accessed
by indexing
Elements are accessed
by indexing
Elements are accessed
by indexing
Values are accessed
by using keys
Elements cant be
accessed using
indexing
Str = “Hello” List = [1, ‘hi’, (3,4)] Tuple = (‘hi’, 1, [2, 3]) Dict = {‘hi’:123,
‘set’:456}
S = {‘hello’, (2,3),
[4,5], 88}
Comparison of Python Data Structures
25
27. WAP to create a dictionary of set of living and non-living beings. Accept a key from the
user and print whether it’s a living or a non-living being.
Dict = {"cat" : "Living", "car" : "non living", "human" : "living", "chair" : "non living", "whale":
"living", "tiger" : "living", "star" : "non living" }
being=input("Enter the keyn")
print(Dict[thing])
Output:
1. 2.
Enter the key Enter the key
star whale
non living living
27