thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionaries are used to store data values in key: value pairs.
A dictionary is a collection which is ordered*, changeable and do not
allow duplicates.
As of Python version 3.7, dictionaries are ordered. Dictionaries are
written with curly brackets, and have keys and values:
Dictionaries are used to store data values in key: value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
When we say that dictionaries are ordered, it means that the items
have a defined order, and that order will not change.
Unordered means that the items does not have a defined order, you
cannot refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can
change, add or remove items after the dictionary has
been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary
print(len(thisdict))
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
Example
String,int, Boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
type()
From Python's perspective, dictionaries are defined as
objects with the data type 'dict':
<class 'dict'>
Python Collections (Arrays)
There are four collection data types in the Python
programming language:
•List is a collection which is ordered and changeable.
Allows duplicate members.
•Tuple is a collection which is ordered and
unchangeable. Allows duplicate members.
•Set is a collection which is unordered, unchangeable*,
and unindexed. No duplicate members.
•Dictionary is a collection which is ordered** and
changeable. No duplicate members.
•When choosing a collection type, it is useful to understand the
properties of that type. Choosing the right type for a particular data set
could mean retention of meaning, and, it could mean an increase in
efficiency or security.
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = This is called a method called get() method to do same
thisdict["model"]
Example
Get the value of the "model" key:
x = thisdict.get("model")
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:
x = thisdict.keys()
The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.Keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
#Make a change in the original dictionary, and see that the
values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
To determine if a specified key is present in a dictionary use the in keyword:
Check if "model" is present in the dictionary :
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
You can change the value of a specific item by
referring to its key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
There are several methods to remove items from a
dictionary:
The pop() method removes the item with the
specified key name
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
class MyClass:
x = 5
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
the __init__() Function
The examples above are classes and objects in their simplest form, and are not really useful in real life
applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary to
do when the object is being created:
Create a class named Person, use the __init__() function to assign values for name and
age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used to create a new object.
The __str__() Function
The __str__() function controls what should be returned when the class object is represented as a string.
If the __str__() function is not set, the string representation of the object is returned:
Example
The string representation of an object WITHOUT the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
The __str__() Function
The __str__() function controls what should be returned when the class object is
represented as a string.
If the __str__() function is not set, the string representation of the object is
returned:
Example
The string representation of an object WITHOUT the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
The string representation of an object WITH the __str__()
function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object.
Let us create a method in the Person class:
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
The self Parameter
The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
Note:
It does not have to be The self parameter
named self , you is acan call itto whatever
reference you like,
the current instance but
of the it has
class, and isto betothe
used first
access parameter
variables of any
that belong class .
to thefunction in the class:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
del p1
Delete the age property from the p1 object:
del p1.age
Create a class named MyClass:
MyClass: x = 5
The pass Statement
class definitions cannot be empty, but if you for some reason have a class definition with no
content, put in the pass statement to avoid getting an error.
Example
class Person:
pass
Try it Yourself »
Python Inheritance
Inheritance allows us to define a class that inherits all the methods
and properties from another class.
Parent class is the class being inherited from, also called base
class.
Child class is the class that inherits from another class, also called
derived class.
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
ho
et
m
m e
na
i nt
pr
a
d
, an
s
rti e
e
rop
p
e
n am
a st
l
nd
e a
am
s tn
ir
f
it h
n ,w
r so
Pe
e d
a m
n
s
as
cl
a
t e
rea
C