0% found this document useful (0 votes)
20 views8 pages

Understanding Python Dictionaries

A dictionary is a mutable, unordered collection of key-value pairs where keys must be unique and immutable, created using curly brackets. You can add, update, access, and remove items using various methods such as square brackets, update(), pop(), and del. Additionally, dictionary methods like keys(), values(), and items() allow for retrieving keys, values, and key-value pairs respectively.

Uploaded by

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

Understanding Python Dictionaries

A dictionary is a mutable, unordered collection of key-value pairs where keys must be unique and immutable, created using curly brackets. You can add, update, access, and remove items using various methods such as square brackets, update(), pop(), and del. Additionally, dictionary methods like keys(), values(), and items() allow for retrieving keys, values, and key-value pairs respectively.

Uploaded by

shazamgaming2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dictionary:

 It is a collection key and value pairs.


 It is mutable data type.
 It is unordered or non-sequential data type.
 Key must be unique and immutable.
 It is created using {} curly brackets.
 Keys and values are separated by colon. i.e. key : value
 Each key value pair is separated by comma. i.e. { key1: value1 , key2 : value2 }

Creating a dictionary :
Example: Create a student dictionary with name s and keys name, class and marks.
s={
'name' : 'Sachin',
'class': 12,
'marks': 75
}

Print a dictionary:
To print a dictionary use following syntax:
print(dictionary_name)

Dictionary Length :
To determine how many items a
dictionary has, use the len() function.

Syntax: len(dictionary_name)
Looping through a dictionary: you can use for loop for this

1. To get values of a dictionary one by one, 2. To get keys of a dictionary one by one,
You can use either of the two ways given You can use either of the two ways given below.
below.

Accessing value of a key:

a.)Using square brackets


Adding or Updating an item in a dictionary:
Adding and updating is done in a same way. If a key already exists then its value will be updated.
If a key doesn’t exist already ,then a new key:value pair is added to the dictionary.
There are two ways for doing so.

a.)Using square brackets b.)Using update() method

Updating a dictionary using update():


Updating a dictionary using square brackets :
In this case key already exists, so just its value is
In this case key already exists, so just its value is updated with the new one.
updated with the new one.
Example : you want to change the name to Ramesh
Example : you want to change the name to Ram
and marks to 89
and marks to 90
Removing Items
These two methods are used to remove items from a dictionary:

a.)Using pop() b.)Using popitem()

Dictionary methods:
1. keys() : It returns a list of all the keys in a dictionary.

syntax
dictionary_name.keys()
2. values() : It returns a list of all the values in a dictionary.

3. items() : It returns a list of all the items (key:value pairs) in a dictionary.

4. clear()
It deletes all the data from the dictionary.
5. fromkeys() : It creates and returns a new dictionary with the given keys.
All the keys will have same value if provided. If no value is provided, None is used as default.

del keyword:

del keyword is used to delete a complete dictionary, list or tuple.


When used with keyname, it can also delete the key:value pair from dictionary.

Deleting a dictionary: In the given example, when we try to print dictionary s1 , it gives error. Because del
keyword has already deleted s1. So it doesn’t exist anymore. Similarly it can be used with any list or tuple.
PREV YEAR QUES:

Common questions

Powered by AI

The 'update()' method is beneficial when updating multiple key-value pairs at once, particularly when merging another dictionary, while direct assignment with square brackets is faster and more straightforward for single entries. Additionally, 'update()' can handle keyword arguments and other iterables that yield key-value pairs .

The unordered nature means that dictionaries do not keep the order of items consistent as they are not indexed by position but by key. This can influence operations where order matters, necessitating transformations or extra data structures for ordered results, impacting algorithm design and performance .

The 'pop()' method removes a specified key from the dictionary, making it ideal when you need to remove a known key-value pair. The 'popitem()' method removes the last inserted key-value pair, useful for adhering to LIFO data management or when specific key ordering is important .

The 'clear()' method is more appropriate as it removes all key-value pairs while keeping the dictionary object intact, allowing continued use or reassignment. 'del' would remove the entire dictionary object from memory, requiring re-creation if further use is needed .

Immutability of keys ensures that the keys cannot be changed, which provides a stable reference point for dictionary operations, while allowing the dictionary to use hash tables for quick data retrieval. If keys were mutable, their hash values could change, causing inconsistencies in data access .

The 'keys()' method returns a list of all keys, 'values()' provides a list of all values, and 'items()' returns a list of all key-value pairs in the dictionary. These methods facilitate easy iteration over dictionary components and are useful for various data manipulation tasks .

The 'pop()' method enhances flexibility by allowing safe removal of a key while optionally returning its value, thus enabling error handling or conditional logic. Unlike 'del', 'pop()' can be used in expressions and is useful when the existence of a key is uncertain .

The 'fromkeys()' method is used to create a new dictionary using the provided keys and assigns a given value to all keys, defaulting to None if no value is specified. Its limitation is that it assigns the same value to all keys, making it unsuitable for scenarios where different initial values are needed for each key .

The 'del' keyword is used to delete an entire dictionary or a specific key-value pair, completely removing it from memory, whereas the 'clear()' method deletes all the data from the dictionary, making it empty but keeping the dictionary object itself in memory .

Dictionary keys must be immutable to ensure they have a consistent hash value, essential for efficient data retrieval and storage. Using a mutable object as a key would risk altering the hash value and corrupting the dictionary’s structure, leading to retrieval errors or data loss .

You might also like