0% found this document useful (0 votes)
7 views4 pages

Python Dictionary Basics and Functions

The document provides an introduction to dictionaries in programming, explaining their structure as key-value pairs and their mutable nature. It covers how to create, access, update, and delete elements within a dictionary, along with examples and built-in functions. The document emphasizes the importance of unique and immutable keys in dictionaries.

Uploaded by

airdrop73838
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)
7 views4 pages

Python Dictionary Basics and Functions

The document provides an introduction to dictionaries in programming, explaining their structure as key-value pairs and their mutable nature. It covers how to create, access, update, and delete elements within a dictionary, along with examples and built-in functions. The document emphasizes the importance of unique and immutable keys in dictionaries.

Uploaded by

airdrop73838
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

Table of contents

INTRODUCTION: Dictionary
Key-value pair
Creating A Dictionary
Iterating Through A Dictionary
Deleting Dictionary Elements
Built-in Dictionary Functions

INTRODUCTION: Dictionary
A dictionary is like a list, but more in general. In a list, index value is an integer, while in a
dictionary index value can be any other data type and are called keys. The key will be used
as a string as it is easy to recall. A dictionary is an extremely useful data storage construct
for storing and retrieving all key value pairs, where each element is accessed (or indexed) by
a unique key. However, dictionary keys are not in sequences and hence maintain no left-to
right order.

It is an un-ordered collection of items where each item consist of a key and a value. It is
mutable (can modify its contents ) but Key must be unique and immutable. Dictionary is also
known as associative array or mapping or hashes .

Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called keys)
and a set of values. Each key maps a value. The association of a key and a value is called a
key-value pair.

Syntax:

my_dict = {‘key1’: ‘value1’,‘key2’: ‘value2’,‘key3’: ‘value3’…‘keyn’: ‘valuen’}

Note: Dictionary is created by using curly brackets(ie. {}).

Example

A={1:"one",2:"two",3:"three"}
print A

output:

{1: ‘one’, 2: ‘two’, 3: ‘three’}

Creating A Dictionary

It is enclosed in curly braces {} and each item is separated from other item by a comma(,).
Within each item, key and value are separated by a colon (:).
Example: -

dict = {‘Subject': ‘Informatic Practices', 'Class': ‘11'}

#Accessing an Item

dict = {'Subject': 'Informatics Practices', 'Class': 11}


print(dict)
print ("Subject : ", dict['Subject'])
print ("Class : ", [Link]('Class'))

OUTPUT

{‘Class’: ‘11’, ‘Subject’: ‘Informatics Practices’} (’Subject : ’, ‘Informatics Practices’) (’Class :


’, 11)

Iterating Through A Dictionary


Following example will show how dictionary items can be accessed through loop.

Example: -

dict = {'Subject': 'Informatics Practices', 'Class': 11}


for i in dict:
print(dict[i])

OUTPUT

Informatics practices 11

Updating Dictionary Elements

We can change the individual element of dictionary.

Example: -

dict = {'Subject': 'Informatics Practices', 'Class': 11}


dict['Subject']='computer science'
print(dict)

OUTPUT

{‘Class’: 11, ‘Subject’: ‘computer science’}

Deleting Dictionary Elements

del, pop() and clear() statement are used to remove elements from the dictionary.
del

Example: -

dict = {'Subject': 'Informatics Practices', 'Class': 11}


print('before del', dict)
del dict['Class'] # delete single element
print('after item delete', dict)
del dict #delete whole dictionary
print('after dictionary delete', dict)

Output

(‘before del’, {‘Class’: 11, ‘Subject’: ‘Informatics Practices’}) (‘after item delete’, {‘Subject’:
‘Informatics Practices’}) (‘after dictionary delete’, )

pop() method is used to remove a particular item in a dictionary. clear() method is used to
remove all elements from the dictionary.

Example: -

dict = {'Subject': 'Informatics Practices', 'Class': 11}


print('before del', dict)
[Link]('Class')
print('after item delete', dict)
[Link]()
print('after clear', dict)

Output

(‘before del’, {‘Class’: 11, ‘Subject’: ‘Informatics Practices’}) (‘after item delete’, {‘Subject’:
‘Informatics Practices’}) (‘after clear’, {})

Built-in Dictionary Functions


len(dict) Gives the total length of the dictionary. It is equal to the number of items in the
dictionary. str(dict) Return a printable string representation of a dictionary type(variable) If
variable is dictionary, then it would return a dictionary type.

Some more examples of Dictionary are:-

Dict1= { } # this is an empty dictionary without any element.

DayofMonth= { January”:31, ”February”:28, ”March”:31, ”April”:30, ”May”:31, ”June”:30,


”July”:31, ”August”:31, ”September”:30, ”October”:31, ”November”:30, ”December”:31}

FurnitureCount = { “Table”:10, “Chair”:13, “Desk”:16, “Stool”:15, “Rack”:15 }


By above examples you can easily understand about the keys and their values. One thing to
be taken care of is that keys should always be of immutable type.

Common questions

Powered by AI

Both del and pop() are used to remove elements from a dictionary; however, they have distinct behaviors. The del method removes a specific item or the entire dictionary based on its argument, but does not return the deleted item. Conversely, pop() removes a specified item by key and returns the value of the removed item. This return feature makes pop() valuable for operations where the removed value is immediately required. Del offers versatility in deleting whole dictionaries, while pop() focuses on individual item removal .

Dictionary elements can be updated by assigning a new value to an existing key or by adding a new key-value pair. Elements can be deleted using the del statement, which can remove specific items or the entire dictionary, or the pop() method, which removes an item by key and returns its value. The clear() method removes all items from the dictionary, emptying it entirely. Del and pop() affect single elements (or the entire dictionary with del), whereas clear() affects all elements but keeps the dictionary structure intact .

Curly brackets in Python dictionaries denote the definition and structure of the dictionary. They encapsulate the key-value pairs, visually distinguishing the dictionary as an unordered collection. The brackets help to easily identify dictionaries within the code and separate them from other types like lists or sets. Inside the brackets, key-value pairs are arranged with colons separating keys from values, and commas separating individual pairs, maintaining clarity in complex or nested data structures .

In dictionaries, keys must be of an immutable type, such as strings, numbers, or tuples, to ensure the integrity and reliability of indexing. Immutability means the keys cannot change, which is crucial as it allows the dictionary to maintain a reliable mapping of keys to values. If keys were mutable, their value could be modified inadvertently, leading to errors or corrupted data lookups. Ensuring key immutability ensures dictionary operations maintain consistency and prevent unexpected behavior .

The len() function, when applied to a dictionary, returns the total number of key-value pairs it contains. This is useful for determining the size of the dictionary. The str() function returns a string representation of the dictionary, providing a readable format of its contents. These functions help to quickly assess the contents and structure of a dictionary .

The unordered nature of dictionaries offers efficient operations for insertion, deletion, and access, contributing to fast average time complexity of O(1) for these operations. This efficiency is because dictionaries do not need to maintain order, unlike lists or arrays, which often require shifting elements. However, the lack of order can hinder operations where element sequence is crucial, such as sorting or iterating in a specific order. Therefore, while dictionaries are ideal for rapid access scenarios, their unordered nature might require complementary sorting or ordered structures for certain tasks .

A dictionary in Python is an unordered collection of items, each consisting of a unique key and a value. Unlike lists, the keys in dictionaries can be any immutable type and are used to index the values, whereas lists use integer indices. Dictionaries are mutable, allowing for the modification of their contents, but the keys themselves must be unique and immutable. The unordered nature means that dictionaries do not maintain a sequence or left-to-right order of elements .

Dictionaries effectively store key-value pairs, offering efficient data retrieval through unique keys. They are more flexible than lists, which require integer indices, enabling the use of descriptive keys that improve code readability and maintenance. Dictionaries excel in scenarios where data is accessed in a non-sequential manner, such as configurations, mappings, and lookups—tasks where quick, direct access to elements by key is crucial. The ability to handle a broad range of key types allows dictionaries to represent complex datasets succinctly .

Associative arrays, mappings, hashes, and Python dictionaries all refer to data structures based on key-value pairing. They provide a way to associate a set of keys with a set of values, where each unique key maps to a value. In different programming contexts, these terms emphasize similar concepts: associative arrays in general use, mappings focusing on relationship semantics, and hashes highlighting hash table-based implementations. Python dictionaries encapsulate these concepts within its specific syntax and operational model .

Iterating through a dictionary can be done using a loop, where each iteration accesses the key-value pair. Because dictionaries are unordered, the order of access is not guaranteed, meaning the elements will not necessarily be retrieved in the order they were entered . For example, using a for loop over the dictionary keys allows the retrieval of each associated value through index access. Python dictionaries since version 3.7 maintain insertion order, but this is not a property to rely on across all implementations .

You might also like