Dictionaries and Structuring Data
Dictionaries and Structuring Data
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))
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}
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= {}
#empty dictionary
dict3= {}
#all false
dict5 = {0:False}
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
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