0% found this document useful (0 votes)
16 views15 pages

Dictionary Notes

A Python dictionary is a mutable data type that stores data in key-value pairs, allowing for easy organization and retrieval of information. Each key must be unique and immutable, while values can be of any type. Key functions include adding, updating, deleting items, and checking membership, making dictionaries versatile for various applications.

Uploaded by

Riaz mir20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views15 pages

Dictionary Notes

A Python dictionary is a mutable data type that stores data in key-value pairs, allowing for easy organization and retrieval of information. Each key must be unique and immutable, while values can be of any type. Key functions include adding, updating, deleting items, and checking membership, making dictionaries versatile for various applications.

Uploaded by

Riaz mir20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Dictionary: Data type:

A dictionary in Python is a special type of data that stores information in pairs — one part is
called a key and the other is its value.
👉 You can think of it like a real dictionary: you look for a word (key) to find its meaning
(value).

A dictionary is an unordered collection of data items, where each item has a key and a value.
You can use the key to quickly find or change its value, just like finding a contact by name in
your phone.

In Python, a dictionary helps you store and organize data in an easy way.
Each piece of data is stored as a key–value pair, such as:
student = {"name": "Ali", "age": 13, "class": 7}

Here, "name", "age", and "class" are keys, and "Ali", 13, and 7 are their values.

A dictionary is a mutable data type — that means we can add, remove, or change data after
creating it.
It does not use numbers for positions like lists do; instead, it uses keys to find data.

A dictionary is a kind of data container that holds many values, but every value is connected
with a name (key).
This makes it easy to store real-world data, like student records, marks, or settings in a game.
A dictionary is created by placing key–value pairs inside curly braces {}, separated by
commas.

Syntax:
dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}

Explanation:

 dictionary_name → name you give to your dictionary (like a


variable name).
 Curly braces {} → used to define a dictionary.
 key1, key2, key3 → unique identifiers (must be immutable, like
strings or numbers).
 value1, value2, value3 → data stored for each key (can be of any
type).
 Each pair is separated by a comma (,).
 Between key and value, we always use a colon (:).
Example 1: Simple Dictionary
student = {
"name": "Ali",
"age": 13,
"class": "7th"
}

print(student)

Explanation:

 "name", "age", and "class" are keys.


 "Ali", 13, and "7th" are their values.
 Together they form key–value pairs.

Output:

{'name': 'Ali', 'age': 13, 'class': '7th'}


Example 2: Empty Dictionary

You can create an empty dictionary and add data later.

student = {}
student["name"] = "Sara"
student["age"] = 12
print(student)

Output:

{'name': 'Sara', 'age': 12}

Example 3: Using dict() Constructor

Python also allows you to make a dictionary using the dict() function.

car = dict(brand="Toyota", model="Corolla", year=2020)


print(car)

Output:

{'brand': 'Toyota', 'model': 'Corolla', 'year': 2020}

Important Points to Remember

1. Keys must be unique.


2. Keys must be immutable (cannot be changed).
3. Values can be any type — numbers, strings, lists, etc.
4. Dictionaries are mutable — you can add, delete, or change items anytime.
5. Dictionaries are unordered — there is no fixed position like in lists.
Dictionary — Functions & Operations

🔹 1. len() Function

Definition:
The len() function tells how many key–value pairs are present in the dictionary.

Syntax:

len(dictionary_name)

Example:

student = {"name": "Ali", "age": 13, "class": "7th"}


print(len(student))

Output:

🔹 2. keys() Function

Definition:
This function returns all the keys from a dictionary.

Syntax:

dictionary_name.keys()

Example:

student = {"name": "Ali", "age": 13}


print(student.keys())

Output:

dict_keys(['name', 'age'])

🔹 3. values() Function

Definition:
The values() function gives all the values stored in the dictionary.

Syntax:
dictionary_name.values()

Example:

student = {"name": "Ali", "age": 13}


print(student.values())

Output:

dict_values(['Ali', 13])

🔹 4. items() Function

Definition:
It returns both keys and values together in the form of pairs (tuples).

Syntax:

dictionary_name.items()

Example:

student = {"name": "Ali", "age": 13}


print(student.items())

Output:

dict_items([('name', 'Ali'), ('age', 13)])

🔹 5. get() Function

Definition:
Used to get the value of a key safely.
If the key doesn’t exist, it returns a default message instead of giving an error.

Syntax:

dictionary_name.get(key, default_value)

Example:

student = {"name": "Ali", "age": 13}


print(student.get("age"))
print(student.get("grade", "Not Found"))

Output:
13
Not Found

🔹 6. update() Function

Definition:
Used to add a new key–value pair or update an existing value in the dictionary.

Syntax:

dictionary_name.update({key: value})

Example:

student = {"name": "Ali", "age": 13}


student.update({"grade": "A"})
print(student)

Output:

{'name': 'Ali', 'age': 13, 'grade': 'A'}

🔹 7. pop() Function

Definition:
Removes a specific key and returns its value.

Syntax:

dictionary_name.pop(key)

Example:

student = {"name": "Ali", "age": 13}


student.pop("age")
print(student)

Output:

{'name': 'Ali'}

🔹 8. popitem() Function

Definition:
Removes the last inserted key–value pair from the dictionary.
Syntax:

dictionary_name.popitem()

Example:

student = {"name": "Ali", "age": 13, "class": "7th"}


student.popitem()
print(student)

Output:

{'name': 'Ali', 'age': 13}

🔹 9. clear() Function

Definition:
Removes all items from the dictionary.

Syntax:

dictionary_name.clear()

Example:

student = {"name": "Ali", "age": 13}


student.clear()
print(student)

Output:

{}

🔹 10. copy() Function

Definition:
Makes an exact copy of the dictionary.

Syntax:

new_dict = dictionary_name.copy()

Example:

student = {"name": "Ali", "age": 13}


new_student = student.copy()
print(new_student)
Output:

{'name': 'Ali', 'age': 13}

🔹 11. fromkeys() Function

Definition:
Creates a new dictionary using a list of keys, all having the same default value.

Syntax:

dict.fromkeys(keys, default_value)

Example:

keys = ['name', 'age', 'grade']


student = dict.fromkeys(keys, 'Not Assigned')
print(student)

Output:

{'name': 'Not Assigned', 'age': 'Not Assigned', 'grade': 'Not Assigned'}

Dictionary Operations

🔹 1. Membership Operator

Definition:
Used to check whether a key exists in a dictionary or not.

Syntax:

key in dictionary_name

Example:

student = {"name": "Ali", "age": 13}


print("name" in student)
print("grade" not in student)

Output:

True
True
🔹 2. Looping Through a Dictionary

Definition:
We can loop through a dictionary to print all keys and values.

Example:

student = {"name": "Ali", "age": 13, "class": "7th"}

for key in student:


print(key, ":", student[key])

Output:

name : Ali
age : 13
class : 7th

🔹 3. Adding or Updating Items

Definition:
You can directly add or change an item by assigning a new value to a key.

Example:

student = {"name": "Ali"}


student["age"] = 13
student["name"] = "Ahmed"
print(student)

Output:

{'name': 'Ahmed', 'age': 13}

🔹 4. Deleting Items

Definition:
You can delete a specific key–value pair using del.

Example:

student = {"name": "Ali", "age": 13}


del student["age"]
print(student)

Output:
{'name': 'Ali'}

🔹 5. Merging Dictionaries

Definition:
Two dictionaries can be combined using the update() method.

Example:

d1 = {"name": "Ali"}
d2 = {"age": 13}
d1.update(d2)
print(d1)

Output:

{'name': 'Ali', 'age': 13}

…………………………………………………
Extra Me

Python Dictionary

1. Store Items in Pairs

A dictionary stores data in the form of pairs.


Each item has two parts:

 Key → acts like a name or label


 Value → the data stored with that key

This is called a key–value pair.

Example:

student = {"name": "Ali", "age": 13}

Here "name" and "age" are keys, while "Ali" and 13 are their values.

🔹 2. Four Things to Remember About Dictionary

1. Mutable → You can change existing key values.


2. No Indexing → Items don’t have number positions like lists.
3. Keys Can’t Be Duplicated → Each key must be unique.
4. Keys Can’t Be Mutable Items → Keys can’t be lists or sets (but values can be
anything).

🔹 3. Creating a Dictionary

(a) Empty Dictionary


d = {}

(b) Homogeneous Dictionary

All keys and values have the same data type (like all strings).
d = {"name": "Ali", "city": "Karachi"}

(c) Mixed Type Dictionary

Keys and values can have different data types.

d = {(1, 2, 3): 1, "hello": "world"}

🔹 4. Types of Dictionary

1️⃣ 1D Dictionary

A simple dictionary that does not contain another dictionary inside it.

di = {'name': 'Ali', 'gender': 'male'}

2️⃣ 2D Dictionary

A dictionary that contains another dictionary inside it.


This type of structure is also called a JSON format.

s = {
'name': 'Nitish',
'college': 'BIT',
'sem': 4,
'subjects': {
'dsa': 50,
'maths': 67,
'english': 34
}
}

💡 In future, you might work with 3D or 4D dictionaries (dictionary within dictionary multiple
times).

🔹 5. JSON Format

JSON means JavaScript Object Notation.


It follows the same format as a Python dictionary and is used when we fetch or send data from
APIs.

Example:

{
"name": "Ali",
"age": 13,
"marks": 88
}

🔹 6. Duplicate Keys

If you create a dictionary with duplicate keys, the last key’s value will replace the earlier ones.

Example:

d5 = {'name': 'Mir', 'name': 'Ali'}


print(d5)

Output:

{'name': 'Ali'}

🧠 Explanation:
Python doesn’t allow duplicate keys, so only the last value is kept.

🔹 7. Accessing or Fetching Values

To get a value from a dictionary, you must use its key.

Example:

student = {'name': 'Ali', 'age': 13}


print(student['name'])

Output:

Ali

🔹 8. Adding New Key–Value Pair

You can add a new pair simply by assigning a new key.

d4 = {'name': 'Ali'}
d4['newkey'] = 'newvalue'
print(d4)

Output:

{'name': 'Ali', 'newkey': 'newvalue'}


🔹 9. Removing Items

You can remove items using these functions:

(a) pop()

Removes a specific key.

d.pop('name')

(b) popitem()

Removes the last key–value pair.

d.popitem()

(c) del

Deletes a specific key.

del d['keyname']

(d) clear()

Removes all items from the dictionary.

d.clear()

🔹 10. Dictionary Operations

(A) Membership Operator

Used to check if a key is present in the dictionary.

Syntax:

'key' in dictionary_name

Example:

s = {'name': 'Ali', 'college': 'PSS', 'age': '33'}


print('name' in s)

Output:

True
(B) Looping / Iteration

You can loop through a dictionary to print all keys and values.

Example:

s = {'name': 'Ali', 'college': 'PSS', 'age': '33'}

for i in s:
print(i, ":", s[i])

Output:

name : Ali
college : PSS
age : 33

🧠 This process is called iteration — going through each item one by one.

✅ Summary for Students

 A dictionary stores data in key–value pairs.


 It is mutable, meaning we can change it.
 Keys must be unique and immutable.
 It has no indexing, only keys are used to access values.
 Supports important operations like add, delete, update, loop, and check.

You might also like