Methods and Functions

Python Dictionary Methods

The python dictionary has a set of predefined methods used to perform various tasks in the dictionary. A dictionary stores a pair of values, one of which is the Key, and the other is the Key-value element.

python dictionary

Source

What is a Python Dictionary?

A python dictionary is a collection of unordered items. Each of these items has a key/value pair. Using some of the built-in dictionary functions users can retrieve their desired key-value pairs. 

How do you declare a Dictionary in Python?

A dictionary in Python is declared using curly braces. The key-value pairs are separated with commas. 

For example:

                    

Dict1 = {1: 'Have', 2: 'a', 3: 'Good', 4:'Day'}

print("\nDictionary having integer keys: ")

print(Dict1)



Dict1 = {'Name': 'Amy', 1: [0, 1, 2, 3, 4]}

print("\nDictionary having mixed keys: ")

print(Dict1)



Output: 

 

Dictionary having integer keys:

{1: 'Have', 2: 'a', 3: 'Good', 4:'Day'}

Dictionary having mixed keys:

{'Name': 'Amy', 1: [0, 1, 2, 3, 4]}

Is dictionary faster than list Python?

When compared to lists, finding elements in dictionaries is much faster. This is because dictionaries in Python look for key-value pairs using a hash table, where the lists look for the key-value pairs from the beginning of the list till the pairs are found.

How do you access a dictionary in python?

A dictionary uses keys to access the elements from the dictionary. The elements can be accessed using the get(). If the user is trying to access an element that does not exist, an error is generated. 

Source Code

                    

my_dict1 = {'name': 'Jacky', 'age': 25}



# Output: Jacky

print(my_dict1['name'])



# Output: 25

print(my_dict1.get('age'))



# If you try to access the keys that don't exist, an error will be generated

print(my_dict.get1('address'))



# KeyError

print(my_dict1['address'])



Output

Jacky

25

None

Traceback (most recent call last):

  File "", line 15, in 

    print(my_dict['address'])

KeyError: 'address'

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.