0% found this document useful (0 votes)
7 views

Dictionaries and Structuring Data

The document explains the concept of dictionaries in Python, highlighting their mutable nature and the use of key-value pairs. It covers various operations such as adding, modifying, and removing items, as well as checking for key existence and using built-in functions. Additionally, it provides examples of creating a student management system using dictionaries to manage student records.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Dictionaries and Structuring Data

The document explains the concept of dictionaries in Python, highlighting their mutable nature and the use of key-value pairs. It covers various operations such as adding, modifying, and removing items, as well as checking for key existence and using built-in functions. Additionally, it provides examples of creating a student management system using dictionaries to manage student records.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

DICTIONARIES AND

STRUCTURING DATA
Like a list, a dictionary is a mutable collection of many values. But unlike indexes for lists,
indexes for dictionaries can use many different data types, not just integers. \
Indexes for dictionaries are called keys, and a key with its associated value is called a key-
value pair.
dictionary is typed with braces, {}
myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
 Dictionaries vs. Lists
 myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud’}
 >>> myCat['size']
'fat'
>>> 'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.’
 >>> spam = ['cats', 'dogs', 'moose']
>>> bacon = ['dogs', 'moose', 'cats']
>>> spam == bacon
False
>>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
>>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
>>> eggs == ham
True
 dictionaries are not ordered, they can’t be sliced like lists.
 birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}

while True:
print('Enter a name: (blank to quit)')
name = input()
if name == ‘ ':
break

➋ if name in birthdays:
➌ print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
➍ birthdays[name] = bday
print('Birthday database updated.')
 Enter a name: (blank to quit)
Alice
Apr 1 is the birthday of Alice
Enter a name: (blank to quit)
Eve
I do not have birthday information for Eve
What is their birthday?
Dec 5
Birthday database updated.
Enter a name: (blank to quit)
Eve
Dec 5 is the birthday of Eve
Enter a name: (blank to quit)
The keys(), values(), and items() Methods
 There are three dictionary methods that will return list-like values of the
dictionary’s keys, values, or both keys and values: keys(), values(), and items().
 they cannot be modified and do not have an append() method
 >>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():
... print(v)

red
42
 A for loop can also iterate over the keys or both keys and values:
 >>> for k in spam.keys():
... print(k)

color
age
>>> for i in spam.items():
... print(i)

('color', 'red')
('age', 42)
 the multiple assignment trick in a for loop to assign the key and value to
separate variables.
 >>> spam = {'color': 'red', 'age': 42}
>>> for k, v in spam.items():
... print('Key: ' + k + ' Value: ' + str(v))

Key: age Value: 42


Key: color Value: red
Checking Whether a Key or Value Exists in a
Dictionary

 >>> spam = {'name': 'Zophie', 'age': 7}


>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False
The setdefault() Method
 To set a value in a dictionary for a certain key only if that key does not already have a
value.
 spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black’
 The setdefault() method offers a way to do this in one line of code.
 The first argument passed to the method is the key to check for, and the second argument
is the value to set at that key if the key does not exist.
 If the key does exist, the setdefault() method returns the key’s value.
 >>> spam = {'name': 'Pooka', 'age': 5}
>>> spam.setdefault('color', 'black')
'black'
>>> spam

{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.setdefault('color', 'white')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
Adding items to the dictionary
 Using key-value assignment: Using a simple assignment statement
where value can be assigned directly to the new key.
 Using update() Method: In this method, the item passed inside the
update() method will be inserted into the dictionary. The item can be
another dictionary or any iterable like a tuple of key-value pairs.
 person = {"name": "Jessa", 'country': "USA", "telephone": 1178}
# update dictionary by adding 2 new keys
person["weight"] = 50
person.update({"height": 6})
# print the updated dictionary
print(person)
# output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50,
'height': 6}
Modify the values of the dictionary keys
 Using key name: We can directly assign new values by using its key name. The
key name will be the existing one and we can mention the new value.
 Using update() method: We can use the update method by passing the key-
value pair to change the value. Here the key name will be the existing one, and the
value to be updated will be new.
 person = {"name": "Jessa", "country": "USA"}
 # updating the country name
 person["country"] = "Canada"
 # print the updated country
 print(person['country’])
 # Output 'Canada’
 # updating the country name using update() method
 person.update({"country": "USA"})
 # print the updated country
 print(person['country’])
 # Output 'USA'
Removing items from the
dictionary
 person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50, 'height': 6}
 # Remove last inserted item from the dictionary
 deleted_item = person.popitem()
 print(deleted_item) # output ('height', 6)
 # display updated dictionary
 print(person)
 # Output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50}
 # Remove key 'telephone' from the dictionary
 deleted_item = person.pop('telephone')
 print(deleted_item) # output 1178
 # display updated dictionary
 print(person)
 # Output {'name': 'Jessa', 'country': 'USA', 'weight': 50}
 # delete key 'weight'
 del person['weight']
 # display updated dictionary
 print(person)
 # Output {'name': 'Jessa', 'country': 'USA'}
 # remove all item (key-values) from dict
 person.clear()
 # display updated dictionary
 print(person) # {}
 # Delete the entire dictionary
 del person
Checking if a key exists

 person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178}

 # Get the list of keys and check if 'country' key is present


 key_name = 'country'
 if key_name in person.keys():
 print("country name is", person[key_name])
 else:
 print("Key not found")
 # Output country name is USA
Join two dictionary
 Using update() method
 dict1 = {'Jessa': 70, 'Arul': 80, 'Emma': 55}
 dict2 = {'Kelly': 68, 'Harry': 50, 'Olivia': 66}

 # copy second dictionary into first dictionary


 dict1.update(dict2)
 # printing the updated dictionary
 print(dict1)
 # output {'Jessa': 70, 'Arul': 80, 'Emma': 55, 'Kelly': 68, 'Harry': 50,
'Olivia': 66}
Add multiple dictionaries inside a single dictionary

 # each dictionary will store data of a single student


 jessa = {'name': 'Jessa', 'state': 'Texas', 'city': 'Houston', 'marks': 75}
 emma = {'name': 'Emma', 'state': 'Texas', 'city': 'Dallas', 'marks': 60}
 kelly = {'name': 'Kelly', 'state': 'Texas', 'city': 'Austin', 'marks': 85}

 # Outer dictionary to store all student dictionaries (nested dictionaries)


 class_six = {'student1': jessa, 'student2': emma, 'student3': kelly}

 # Get student3's name and mark


 print("Student 3 name:", class_six['student3']['name'])
 print("Student 3 marks:", class_six['student3']['marks'])

 # Iterating outer dictionary


 print("\nClass details\n")
 for key, value in class_six.items():
 # Iterating through nested dictionary
 # Display each student data
 print(key)
 for nested_key, nested_value in value.items():
 print(nested_key, ':', nested_value)
 print('\n')
 Output

 Student 3 name: Kelly


 Student 3 marks: 85

 Class details

 student1
 name: Jessa
 state: Texas
 city: Houston
 marks: 75

 student2
 name: Emma
 state: Texas
 city: Dallas
 marks: 60

 student3
 name: Kelly
 state: Texas
 city: Austin
 marks : 85
Sort dictionary
 dict1 = {'c': 45, 'b': 95, 'a': 35}

 # sorting dictionary by keys


 print(sorted(dict1.items()))
 # Output [('a', 35), ('b', 95), ('c', 45)]

 # sort dict keys


 print(sorted(dict1))
 # output ['a', 'b', 'c']

 # sort dictionary values


 print(sorted(dict1.values()))
 # output [35, 45, 95]
Built-in functions with dictionary

 max() and min()


 As the name suggests the max() and min() functions will return the keys
with maximum and minimum values in a dictionary respectively.
 dict = {1:'aaa',2:'bbb',3:'AAA'}
 print('Maximum Key',max(dict)) # 3
 print('Minimum Key',min(dict)) # 1
all()

 When the built-in function all() is used with the dictionary the return
value will be true in the case of all-
Few things to note here are
 Only key values should be true
 The key values can be either True or 1 or ‘0’
 0 and False in Key will return false
 An empty dictionary will return true.
 #dictionary with both 'true' keys
 dict1 = {1:'True',1:'False'}
 #dictionary with one false key
 dict2 = {0:'True',1:'False'}
 #empty dictionary
 dict3= {}

 #'0' is true actually


 dict4 = {'0':False}

 print('All True Keys::',all(dict1))


 print('One False Key',all(dict2))
 print('Empty Dictionary',all(dict3))
 print('With 0 in single quotes',all(dict4))
Output
All True Keys:: True
One False Key False
Empty Dictionary True
With 0 in single quotes True
any()
 any() function will return true if dictionary keys contain anyone false which could be 0 or false.
 #dictionary with both 'true' keys
 dict1 = {1:'True',1:'False'}

 #dictionary with one false key


 dict2 = {0:'True',1:'False'}

 #empty dictionary
 dict3= {}

 #'0' is true actually


 dict4 = {'0':False}

 #all false
 dict5 = {0:False}

 print('All True Keys::',any(dict1))


 print('One False Key ::',any(dict2))
 print('Empty Dictionary ::',any(dict3))
 print('With 0 in single quotes ::',any(dict4))
Replace Dictionary Values From Other
Dictionary

 # initializing D1 - first dictionary


 D1 = {'first_name' : 'Jim', 'age' : 23, 'height' : 6.0 , 'job' : 'developer', 'company': 'XYZ'}

 # initializing D2 - - first dictionary
 D2 = {'age' : 35, 'job' : 'senior data analyst'}

 for key in D1:

 # checking if key present in dict2

 if key in D2:
 D1[key] = D2[key]

 # printing the details
 print("The original dictionary: " + str(D1))
 print("The updated dictionary: " + str(D2))
Student management system in
Python
 Problem Statement: Write a program to build a simple Student
Management System using Python which can perform the following
operations:
 Accept
 Display
 Search

 Delete
 Update
 # This is simplest Student data management program in python
 # Create class "Student"
 class Student:
 # Constructor
 def __init__(self, name, rollno, m1, m2):
 self.name = name
 self.rollno = rollno
 self.m1 = m1
 self.m2 = m2
 # Function to create and append new student
 def accept(self, Name, Rollno, marks1, marks2):
 # use ' int(input()) ' method to take input from user
 ob = Student(Name, Rollno, marks1, marks2)
 ls.append(ob)
 # Function to display student details
 def display(self, ob):
 print("Name : ", ob.name)
 print("RollNo : ", ob.rollno)
 print("Marks1 : ", ob.m1)
 print("Marks2 : ", ob.m2)
 print("\n")
 # Search Function
 def search(self, rn):
 for i in range(ls.__len__()):
 if(ls[i].rollno == rn):
 return i
 # Delete Function
 def delete(self, rn):
 i = obj.search(rn)
 del ls[i]
 # Update Function
 def update(self, rn, No):
 i = obj.search(rn)
 roll = No
 ls[i].rollno = roll

 # Create a list to add Students


 ls = []
 # an object of Student class
 obj = Student('', 0, 0, 0)

 print("\nOperations used, ")


 print("\n1.Accept Student details\n2.Display Student Details\n3.Search Details of a Student\n4.Delete Details of Student\
n5.Update Student Details\n6.Exit")
 # ch = int(input("Enter choice:"))
 # if(ch == 1):
 obj.accept("A", 1, 100, 100)
 obj.accept("B", 2, 90, 90)
 obj.accept("C", 3, 80, 80)
 # elif(ch == 2):
 print("\n")
 print("\nList of Students\n")
 for i in range(ls.__len__()):
 obj.display(ls[i])
 # elif(ch == 3):
 print("\n Student Found, ")
 s = obj.search(2)
 obj.display(ls[s])
 # elif(ch == 4):
 obj.delete(2)
 print(ls.__len__())
 print("List after deletion")
 for i in range(ls.__len__()):
 obj.display(ls[i])
 # elif(ch == 5):
 obj.update(3, 2)
 print(ls.__len__())
 print("List after updation")
 for i in range(ls.__len__()):
 obj.display(ls[i])
 # else:
 Operations used,

 1.Accept Student details


 2.Display Student Details
 3.Search Details of a Student
 4.Delete Details of Student
 5.Update Student Details
 6.Exit
 List of Students
 Name : A
 RollNo : 1
 Marks1 : 100
 Marks2 : 100
 Name : B
 RollNo : 2
 Marks1 : 90
 Marks2 : 90
 Name : C
 RollNo : 3
 Marks1 : 80
 Marks2 : 80
 Student Found,
 Name : B
 RollNo : 2
 Marks1 : 90
 Marks2 : 90
 2
 List after deletion
 Name : A
 RollNo : 1
 Marks1 : 100
 Marks2 : 100

 Name : C
 RollNo : 3
 Marks1 : 80
 Marks2 : 80
 2
 List after updation
 Name : A
 RollNo : 1
 Marks1 : 100
 Marks2 : 100
 Name : C
 RollNo : 2
 Marks1 : 80
 Marks2 : 80

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy