DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


What is a Dictionary in Python?

  • 12 minutes read
  • 105 Views
What is a Dictionary in Python?

    Table of Contents

What is a Dictionary in Python?

Python Dictionary or Dictionary in Python is a data-structure in Python that is also known as associative array. A python dictionary is used to store data values in key:value pair. Each item has a key and a corresponding value that is expressed as a pair (key: value). They are optimised to retrieve values when the key is known.

Are Python Dictionaries ordered?

In Python 3.6 and beyond, dictionaries are ordered data structures. It means that a Python dictionary keeps the order of the element in which it is added to the dictionary.

Are Python Dictionaries mutable?

Yes, dictionaries in Python are mutable and you can add, delete and update an item of a Python Dictionary.

Are Python Dictionaries hashable?

No, a dictionary in Python is not hashable and you can not use a dictionary as a key in another dictionary.

Can a dictionary has duplicate keys?

No, the keys in a dictionary are much like a set, which is a collection of hashable and unique objects. Because the objects need to be hashable, mutable objects can’t be used as dictionary keys.

How to create a Dictionary in Python ?

You can easily create a Python Dictionary or Dictionary in Python by enclosing comma-separated key-values pairs in curly brackets ({}), where the key and values are separated by a colon ‘:’.

a_dictionary = {
    <key>: <value>,
    <key>: <value>,
      .
      .
      .
    <key>: <value>
}

A dictionary in Python can also be created by using the built-in function called dict().

a_dictionary = dict([(1, 'Saral'), (2, 'Gyaan')])

print(a_dictionary)

# Output 

{1: 'Saral', 2: 'Gyaan'}

How to create an empty dictionary in Python?

If you want to create an empty dictionary in python, you can use the following code

a_dictionary = {}
b_dictionary = dict()

print(a_dictionary, type(a_dictionary))
print(b_dictionary, type(b_dictionary))

# Output 

{} <class 'dict'>
{} <class 'dict'>

How to create a Dictionary in Python using Comprehension

Using Dictionary comprehension is an elegant way to create a dictionary in Python. It can be used like list comprehensions

all_squares = {i:i**2 for i in range(1,11)}
print(all_squares)

# Output

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

How to access an element from a Python Dictionary ?

Accessing element from a python dictionary is quite easy, instead of using indexes like Python Lists, dictionary use keys in square brackets :-

a_dictionary = {'name' : 'Saral', 'age' :33}

print(a_dictionary['name'])
print(a_dictionary['age'])

# Output

Saral
33

However, if we pass a key in the square brackets that is not present in the dictionary, it will through a key error.

print(a_dictionary['email'])

# Output

KeyError: 'email'

To overcome this KeyError, we can use get() method instead. If the key is not present, it will return None instead of throwing an error

a_dictionary = {'name' : 'Saral', 'age' :33}

print(a_dictionary.get('name'))
print(a_dictionary.get('age'))
print(a_dictionary.get('email'))

# Output

Saral
33
None

How to iterate through a dictionary in Python?

You can iterate through a Python Dictionary using either of the four following ways :

  • Iterating through keys directly
  • Iterating through .items()
  • Iterating through .keys()
  • Iterating through .values()

Iterating a Python Dictionary through keys directly

You can iterate through a Python Dictionary by directly using the keys:-

a_dictionary = {'name' : 'Saral', 'age' :33}

for key in a_dictionary:
    print(key)

# Output
name
age

However, if you also want to get the values, you can use the following code:-

a_dictionary = {'name' : 'Saral', 'age' :33}

for key in a_dictionary:
    print(key, a_dictionary[key])

# Output
name Saral
age 33

Iterating a Python Dictionary through .items()

You can also iterate through a Python Dictionary using .items()

a_dictionary = {'name' : 'Saral', 'age' :33}

for item in a_dictionary.items():
    print(item)


# Output

('name', 'Saral')
('age', 33)

Here each item i.e. key and value pair is a tuple. You can check it as under:-

a_dictionary = {'name' : 'Saral', 'age' :33}

for item in a_dictionary.items():
    print(type(item))

# Output 

<class 'tuple'>
<class 'tuple'>

You can also unpack this tupe while iterating to get the key, value directly.

a_dictionary = {'name' : 'Saral', 'age' :33}

for key, value in a_dictionary.items():
    print(f'{key} ---> {value}')


# Output

name ---> Saral
age ---> 33

Note- Here I have used Python f-strings, you can read more about them from here.

Iterating a Python Dictionary through .keys()

You can get the list of all the keys present in a Python Dictionary by using the following code:-

a_dictionary = {'name' : 'Saral', 'age' :33}
print(a_dictionary.keys())

# Output

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

And then you can iterate through these like under:-

for key in a_dictionary.keys():
    print(key)
    print(f'{key} ---> {a_dictionary[key]}')

# Output

name
name ---> Saral
age
age ---> 33

Iterating a Python Dictionary through .values()

You can get the list of all the values present in a Python Dictionary by using the following code:-

a_dictionary = {'name' : 'Saral', 'age' :33}
print(a_dictionary.values())

# Output

dict_values(['Saral', 33])

And then you can iterate through these like under:-

for value in a_dictionary.values():
    print(value)

# Output

Saral
33

How to change an element in Python Dictionary?

As discussed above, the python dictionaries are mutable, hence we can change an element of the python dictionary by using the following code:-

a_dictionary = {'name' : 'Saral', 'age' :33}
print(a_dictionary)

a_dictionary['age'] = 34

print(a_dictionary)

# Output

{'name': 'Saral', 'age': 33}
{'name': 'Saral', 'age': 34}

How to add a new element to Python Dictionary?

In the above example, we only changed the value of the key which was already present in the dictionary. However, we can also easily add a new key value pair to the dictionary. It is like appending a new element to the dictionary and the new key, value pair would be added at the last ( The dictionaries are ordered for Python 3.6 and beyond)

a_dictionary['email'] = 'admin@saralgyaan.com'
print(a_dictionary)

# Output
{'name': 'Saral', 'age': 34, 'email': 'admin@saralgyaan.com'}

How to add multiple new items/elements to a Python Dictionary?

We can also add a new element to a Python Dictionary by using .update() method. The advantage of using .update() method is that, we can use it to add multiple items to an existing dictionary in one go.

a_dictionary.update({'email': 'admin@saralgyaan.com'})
print(a_dictionary)

a_dictionary.update([('company', 'Saral Gyaan'), ('country', 'India')])
print(a_dictionary)

# Output

{'name': 'Saral', 'age': 34, 'email': 'admin@saralgyaan.com'}
{'name': 'Saral', 'age': 34, 'email': 'admin@saralgyaan.com', 'company': 'Saral Gyaan', 'country': 'India'}

How to insert a new element in a Python Dictionary at specific index?

There is no inbuilt method to insert a new element at a specific index of the Python Dictionary. However, there are few tricks using which you can insert the element at a specific index. If you want to insert an element at the begining of an existing dictionary, you can use th following code :-

a_dictionary = {'name' : 'Saral', 'age' :33}

a_dictionary = {'country' : 'India', **a_dictionary}
print(a_dictionary)

# Output

{'country': 'India', 'name': 'Saral', 'age': 33}

However, if you want to insert the item with index number, you can create a single line lambda function and then use it to insert the element

insert = lambda _dict, obj, pos: {k: v for k, v in (list(_dict.items())[:pos] + list(obj.items()) + list(_dict.items())[pos:])}

a_dictionary = insert(a_dictionary, {'email':'admin@saralgyaan.com'}, 1)

print(a_dictionary)

# Output

{'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}

How to remove/delete an element from a Python Dictionary?

There are various ways using which you can delete an element from a Python Dictionary like using del keyword, pop(), popitem() method or clear() method.

Remove/delete an element using pop() method

You can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value.

a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}

print(a_dictionary.pop('country'))

print(a_dictionary)

# Output

India
{'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}

The first print statement is the value returned by the pop() method.

Remove/delete an element using popitem() method

popitem() method can be used to remove and return an arbitrary key value item from the dictionary. It removes the last item of the ordered dictionary.

a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}

print(a_dictionary.popitem())

print(a_dictionary)

# Output

('age', 33)
{'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral'}

Here, the first print statement returns the key:value pair.

Remove/delete an element using del keyword

Alternatively, you can use the del keyword with the key to remove the specific key:value pair. It won’t return the removed key or value.

a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}

del a_dictionary['country']

print(a_dictionary)

# Output

{'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}

You can also use the del keyword to delete the entire dictionary.

a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}

del a_dictionary

print(a_dictionary)

# Output

Traceback (most recent call last):
  File "D:\official\TRS\TRS\14.10\python work\upwork_1.py", line 65, in <module>
    print(a_dictionary)
NameError: name 'a_dictionary' is not defined

Since, the del keyword deleted a_dictionary in the second line, we get an error if we try to print the dictionary after that.

Remove/delete all element using clear() method

You can also clear all the contents of the dictionary using clear() method. Unlike del, it only deletes the elements and not the dictionary itself and you would be left with an empty dictionary

a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}

a_dictionary.clear()

print(a_dictionary)

# Output

{}

Python Dictionary Methods

Followings are the few important Python Dictionary Methods

Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
keys() Returns a new object of the dictionary's keys.
pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new object of the dictionary's values

Python Dictionary Built-in methods

Following are few Python Dictionary built-in methods

Function Description
all() Return True if all keys of the dictionary are True (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
len() Return the length (the number of items) in the dictionary.
cmp() Compares items of two dictionaries. (Not available in Python 3)
sorted() Return a new sorted list of keys in the dictionary.

Related Posts

If __name__ == '__main__' in Python
By Udit Vashisht

What does if __name__ == ‘__main__‘in python means?

In python, you must have come accross the following code :-

if __name__ == '__main__': main() 

In this tutorial, we will learn in detail what does the above statement means. As per official documentation:

‘__main__‘ is the name of the ...

Read More
Chapter 6 - Data Types & Variables
By Udit Vashisht

Variables and Identifiers in Python

If we go by the dictionary meaning ‘Variable’ is something which is ‘able to be changed or adapted’. Which is true to much extent in terms of Python programming language also. Variable is basically a reference to the memory location where an object is ...

Read More
Use Python to send emails
By Udit Vashisht

How to send emails using Python?

We can easily send emails using Python by using the following steps:-
1. Setting up the SMTP server using smtp.ehlo() and smtp.starttls().
2. Logging in to your account using smtp.login().
3. Creating a message by adding subject and body.
4. ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python