Python Datatype - Part 5 (Dictionary)

Python Datatype - Part 5 (Dictionary)

As we learnt earlier Dictionary is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Set.

  • 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 (key).
  • Dictionary items are presented in key: value pairs, and can be referred to by using the key name.

Example:

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}
print(mydict)        

Print the "courses" value of the dictionary:

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict["courses"])        

Dictionary Items Are Changeable

We can change, add or remove items after the dictionary has been created.

Duplicates Not Allowed

In Dictionaries duplicated key is not allowed (i.e. two items with the same key). it will not show error when duplication occurs rather the last item will override the earlier once:

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9,

  "CGPA": 2.0

}

print(mydict)        

Dictionary Length

The len() method is use to determine the number of item in a dictionary

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(len(mydict))        

Dictionary Items - Data Types

The values of item in a dictionary can be of any datatype

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9,

  "courseList": ["COSC 101", "MATH 102", "ENGL 111", "STAT 112"]

}

print(mydict)        

Access Dictionary Items

Accessing Items

To access an item the key of the item will be reference inside square brackets

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict["name"])        

The get() method ca also be sue to archive the same result

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict.get("name"))        

Get Keys Method

The keys() method will return a list of all the keys in the dictionary.

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict.keys())        

Get Values Method

The values() method will return a list of all the values in the dictionary.

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict.values())        

Get Items Method

The items() method will return each item in a dictionary, as tuples in a list.

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict.items())        

Check if Key Exists

The 'in' keyword is use to check if a key exist in a dictionary

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

if "courses" in mydict:

  print("Yes, 'courses' is one of the keys in the mydict dictionary")        

Change Dictionary Items

Add New Item

You can add a new item to a dictionary by reference to the key inside square brackets and equating to the value.

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict)

mydict["year"] = 2011;

print(mydict)        

Change Values

You can change the value of an item by reference to the key inside square brackets and equating to the new value.

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict)

mydict["courses"] = 11;

print(mydict)        

Update Dictionary

update() method can also be use to add item to dictionary and also to update the value of an item with the items from the given argument.

The argument must be a dictionary, or an iterable object with key: value pairs.

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict)

mydict.update({"courses": 11, "year": 2011})

print(mydict)        

Remove Dictionary Items

There are various ways to remove items from a dictionary: pop(), popitem(), clear() methods and del keyword

pop()

Method removes the item with the specified key

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict)

mydict.pop("courses")

print(mydict)        

popitem()

Removes the last inserted item

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict)

mydict.popitem()

print(mydict)        

clear()

Method empties the dictionary

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict)

mydict.clear()

print(mydict)        

del

Keyword removes the item with the specified key

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

print(mydict)

del mydict["CGPA"]

print(mydict)        

Note: The del keyword can also delete the dictionary completely (del mydict)

Loop Dictionaries

Dictionary can be loop through to print key, value or both key and value. This can be done in various ways as demonstrated below:

- Print key names one by one

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

for x in mydict:

  print(x)        

- Print values one by one

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

for x in mydict:

  print(mydict[x])        

- Print key names one by one using the keys() method

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

for x in mydict.keys():

  print(x)        

- Print values one by one using the values() method

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

for x in mydict.values():

  print(x)        

- Print bothe keys and values using the items() method

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

for x, y in mydict.items():

  print(x + ":", y)        

Copy a Dictionary

copying a dictionary can be done in 2 basic ways:

using copy() method

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

mydict2 = mydict.copy()

print(mydict2)        

using the dict() constructor

mydict = {

  "id": "ST001",

  "name": "Aisha Yahaya",

  "courses": 9,

  "CGPA": 3.9

}

mydict2 = dict(mydict)

print(mydict2)        

Note: doing mydict = mydict2 will not copy mydict to mydict2 rather it will make mydict2 a reference to mydict. meaning that changes made in mydict will automatically be made in mydict2

Nested Dictionaries

This is when a dictionary contain dictionaries

students = {

	"student1": {

  		"id": "ST001",

  		"name": "Aisha Yahaya",

  		"courses": 9,

  		"CGPA": 3.9

	},

	"student2": {

  		"id": "ST002",

  		"name": "Halimat Abdulmutalib",

  		"courses": 10,

  		"CGPA": 4.5

	},

	"student3": {

  		"id": "ST003",

  		"name": "Abdulmutalib Idris",

  		"courses": 9,

  		"CGPA": 3.0

	}

}

print(students)        

Optionally it can also be created like this:

student1 = {

  	"id": "ST001",

  	"name": "Aisha Yahaya",

  	"courses": 9,

  	"CGPA": 3.9

}

student2 = {

  	"id": "ST002",

  	"name": "Halimat Abdulmutalib",

  	"courses": 10,

  	"CGPA": 4.5

}

student3 = {

  	"id": "ST003",

  	"name": "Abdulmutalib Idris",

  	"courses": 9,

  	"CGPA": 3.0

}

students = {

  "student1": student1,

  "student2": student2,

  "student3": student3

}

print(students)        

Access Items in Nested Dictionaries

Using square brackets:

student1 = {

  	"id": "ST001",

  	"name": "Aisha Yahaya",

  	"courses": 9,

  	"CGPA": 3.9

}

student2 = {

  	"id": "ST002",

  	"name": "Halimat Abdulmutalib",

  	"courses": 10,

  	"CGPA": 4.5

}

student3 = {

  	"id": "ST003",

  	"name": "Abdulmutalib Idris",

  	"courses": 9,

  	"CGPA": 3.0

}

students = {

  "student1": student1,

  "student2": student2,

  "student3": student3

}

print(students["student2"]["name"])        

Using loops:

student1 = {

  	"id": "ST001",

  	"name": "Aisha Yahaya",

  	"courses": 9,

  	"CGPA": 3.9

}

student2 = {

  	"id": "ST002",

  	"name": "Halimat Abdulmutalib",

  	"courses": 10,

  	"CGPA": 4.5

}

student3 = {

  	"id": "ST003",

  	"name": "Abdulmutalib Idris",

  	"courses": 9,

  	"CGPA": 3.0

}

students = {

  "student1": student1,

  "student2": student2,

  "student3": student3

}

for x in students:

  for y in students[x]:

    print(students[x][y])        



Abdulmutalib Idris

Head of IT and Media / Full Stack Developer @ Agro Preciso LTD

1 年

I thought so too. Thank you for always following the class and sharing your thoughts

回复
Isiaka Idris

????? ??????? ??????? ??????? ?? ????? ? ??????? ???? ??? ??????? ??????.

1 年

Most beautiful of all the data structures so far!

回复

要查看或添加评论,请登录

Abdulmutalib Idris的更多文章

  • Improving Nigerian Education Through School Management Systems

    Improving Nigerian Education Through School Management Systems

    The Nigerian education sector faces numerous challenges, particularly at the higher institution level. These include…

  • Python Lambda

    Python Lambda

    Is a function that take as many arguments as possible but can only have one expression. They are also consider…

  • Python Functions

    Python Functions

    A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a…

    2 条评论
  • Python Conditional and Loop Statements

    Python Conditional and Loop Statements

    If ..

    1 条评论
  • Python Datatype - Part 4 (Sets)

    Python Datatype - Part 4 (Sets)

    Python Sets As we learnt earlier Set is one of 4 built-in data types in Python used to store collections of data, the…

    1 条评论
  • Python Datatype - Part 3 (Tuples)

    Python Datatype - Part 3 (Tuples)

    Python Tuples As we learnt in the last class there are datatype use to store multiple items in single variable. Python…

  • Python Datatype - Part 2 (Lists)

    Python Datatype - Part 2 (Lists)

    Python Lists There are datatype use to store multiple items in single variable. Python have 4 built-in datatype that…

    1 条评论
  • Python Datatype - Part 1

    Python Datatype - Part 1

    In the last class we talked about variables and we said variable data type is whatever values are assigned to the…

  • Python Variables

    Python Variables

    In python variables are the reserved memory locations used for storing values. In python a built-in id() function…

  • Python Indentation, Multi-line Statements, and Quotations

    Python Indentation, Multi-line Statements, and Quotations

    Python Indentation The spaces left at the beginning of a code line is called indentation. In other languages indenting…

    1 条评论

社区洞察

其他会员也浏览了