[Go to site: main page, start]

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

Python Dictionary Overview and Usage

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)
25 views15 pages

Python Dictionary Overview and Usage

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

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([Link]())

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([Link]())

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([Link]())

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([Link]("age"))
print([Link]("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}


[Link]({"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}


[Link]("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"}


[Link]()
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}


[Link]()
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 = [Link]()
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:

[Link](keys, default_value)

Example:

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


student = [Link](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}
[Link](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.

[Link]('name')

(b) popitem()

Removes the last key–value pair.

[Link]()

(c) del

Deletes a specific key.

del d['keyname']

(d) clear()

Removes all items from the dictionary.

[Link]()

🔹 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.

Common questions

Powered by AI

The 'popitem()' method removes and returns the last inserted key-value pair, while 'pop()' removes a specified key and returns its value. 'popitem()' is particularly useful in scenarios where the most recently inserted data needs to be processed or removed, functioning effectively like a stack's 'pop' operation. This method is useful in situations like undo operations, where the latest changes are processed first .

A Python dictionary being unordered means there is no guaranteed sequence or position for key-value pairs, which differs from lists where positions are fixed. This characteristic implies that operations like sequential access are not inherently predictable based on insertion order, although Python 3.7 and later preserve insertion order as an implementation detail. The unordered nature of dictionaries makes them ideal for lookups, modifications, and deletions by key, rather than positional operations. This trait affects programming by encouraging the use of dictionaries for fast data retrieval via keys and flexible updates rather than ordered data manipulation .

Keys in Python dictionaries must be immutable to ensure that their hash values remain constant and reliable for mapping, which is crucial for the underlying hash table data structure used by dictionaries. This requirement means that keys cannot be types like lists or sets, which are mutable. Consequently, the design of a dictionary's structure allows only immutable types such as strings, numbers, or tuples as keys, ensuring consistent and predictable behavior .

The 'update()' function allows merging two dictionaries by adding key-value pairs from one dictionary to another. If duplicate keys are present, the values from the second dictionary (the argument to 'update()') will overwrite the values in the original dictionary for those keys. This functionality is crucial for ensuring that the dictionary reflects the most recent or highest-priority values .

One major advantage of using Python dictionaries over lists is the ability to efficiently access, insert, or update data by key, typically in constant time, whereas lists require linear time to find and modify elements based on their positions. A limitation of dictionaries, however, is that they do not preserve order (though insertion order is maintained in Python 3.7+ as a side effect), making them less suitable for operations that require ordered data retrieval .

The 'fromkeys()' method creates a new dictionary with specified keys, each initialized with the same default value. This method is particularly useful for initializing a dictionary where multiple keys need to share the same initial value. For instance, it can be used to initialize configuration settings where different options default to a common placeholder indicating they are not yet set or configured .

Python dictionaries are structurally similar to JSON objects, both utilizing key-value pairs for data representation. This similarity is significant in web development as it facilitates smooth data interchange between Python applications and web services or JavaScript-based front-end frameworks. This allows seamless translation between the server-side data structures and JSON data used for APIs, promoting integration and data manipulation across different environments .

If dictionary keys were allowed to be mutable, it would fundamentally disrupt the integrity of the hash table, which relies on the immutability of keys to compute stable hash values. Practically, this would lead to unpredictable behavior, potential hash collisions, and difficulties maintaining consistent dictionary states, undermining efficiency in key-value pair lookups. Additionally, it would necessitate additional complexity in handling key changes and impact the performance benefits associated with constant-time complexity for typical dictionary operations .

The benefits of using a nested dictionary, or 2D dictionary, in Python include structured data representation that enables complex data storage and easy access to hierarchical data levels, similar to JSON objects. However, potential drawbacks include increased complexity in coding, managing, and accessing nested structure, leading to higher chances of errors, especially in handling deeply nested dictionaries. Additionally, readability and maintainability issues can arise from convoluted nested accesses without clear documentation .

The 'get()' function in Python dictionaries is used to safely access a value associated with a specified key. If the key does not exist, 'get()' allows you to return a default value instead of raising a KeyError, which occurs when a key is directly accessed and does not exist. This makes 'get()' useful for avoiding errors and providing a fallback value .

You might also like