logo
Icon
Master Data Analytics Program

Python Dictionary: Syntax, Method, Example, More

1 mins read

Last updated: 11 Feb 2025

2866 views

0%
Master Data Analytics Program

  • Introduction
  • What is a Dictionary in Python?
  • Python Dictionary Syntax
  • Creating a Dictionary in Python
  • Adding elements to a Dictionary
  • Accessing Elements of a Dictionary
  • Deleting Elements in a Dictionary
  • Python Dictionary Methods

Introduction

A Python dictionary is used to store data in a key-value pair, and it can replicate a real-world arrangement that contains a value for a specified key. We can’t change its data structure, and it is defined using keys and values.

In a dictionary, a key is made of a single element, whereas a value can be of any data type, such as a tuple, list, integer, etc. Keys are immutable objects in Python.

What is a Dictionary in Python?

Dictionary is one of the four built-in data structures in Python used to store data in key-value pairs. A key works as a unique identifier for an element and an attribute to locate the data in the memory. A value is the data related to that key. Values can be of any data type, but keys are immutable, so we can change them to only numbers, strings, or tuples

Although dictionaries store information, such as definitions and words, they can be used for various other purposes. As dictionaries are mutable, we can’t change them once created. Also, they are unordered, which means the items in a dictionary are not stored in any specific order.

Python Dictionary Syntax

dict_var = {key1 : value1, key2 : value2, …..}

Key Points to Remember

  • Keys can be only a single element.

  • Keys are case-sensitive, so a name written in uppercase or lowercase is treated differently.

Creating a Dictionary in Python

Creating a Python dictionary is as easy as placing the required key and value pairs inside curly braces. The elements are separated using commas. Out of the value pairs that a dictionary holds, one is key while the other is its key:value. The key, which must be immutable, is placed on the left side of the colon (:) and can be repeated. 

The value, any data type, is on the right and can be duplicated. We use a comma to separate each key-value pair. 

Please note that keys in a dictionary are case-sensitive. The same name written in different cases will be treated differently. 

We use the built-in data type to create a dictionary, which stores all data types, such as strings, integers, and lists. The dictionary data type is the same as a list but uses keys rather than indexes to look up values. 

When we use the dict() function to create a Python dictionary, it takes two arguments:

  • A list of keys

  • A list of values

Please Note

{} is used to place the required key and value pairs within.

: is used to separate key-value pairs.

, is used to separate multiple key-value pairs. 

Syntax

my_dic = {'key1' : 'value1', 'key2' : 'value2', .....,'key_n': 'value_n'}

Example

address = {
    "name" " Wscubetech",
    "location1" : "jodhpur",
    "location2" : "jaipur"
}

Adding elements to a Dictionary

Python dictionaries are mutable data structures, so we can store key-value pairs in them. Once we create a dictionary, we can add, remove, or update elements using different methods. 

We can use the built-in update() method to update an existing value in a dictionary. It requires a key and a value as arguments, and the key must be assigned a value. We can also add nested key values to an existing dictionary. 

When you add a value and the key value exists in the dictionary, the value is updated; otherwise, a new key value is added to the dictionary. 

Example

address = {
    "name": " Wscubetech"
}

address['location1'] = "jaipur"
address.update({'location2' : 'jodhpur'})
print(address)

Output:

{'name': ' Wscubetech', 'location1': 'jaipur', 'location2': 'jodhpur'}

Accessing Elements of a Dictionary

We can access an element or item of a dictionary by referring to its key name. A key can be used inside square brackets to access values in a dictionary. We also use square brackets for indexing and slicing Python strings.

Example

address = {'name': ' Wscubetech', 'location1': 'jaipur', 'location2': 'jodhpur'}
print(address['name'])
print(address['location1'])
print(address['location2'])

Output:

Wscubetech
jaipur
jodhpur

Deleting Elements in a Dictionary

We can delete elements of a dictionary or the entire dictionary using the del keyword. 

We also use the pop() method to remove an element. This method takes a key value as an argument and deletes the key-value pair from the dictionary. If the key doesn’t exist in the dictionary, the pop() method will raise an error. 

The popitem() method is used to delete an arbitrary element from the dictionary. The method deletes a random key-value pair and returns it as a tuple. If the dictionary is empty, it will throw a KeyError. 

Example

address = {'name': ' Wscubetech', 'location1': 'jaipur', 'location2': 'jodhpur', 'course':'python'}
del address['name']  #remove name key
print(address)  
address.pop('location2')  #remove location2 key
print(address)
address.popitem()  #remove last key-value pair
print(address)

Output:

{'location1': 'jaipur', 'location2': 'jodhpur', 'course': 'python'}
{'location1': 'jaipur', 'course': 'python'}
{'location1': 'jaipur'}

Python Dictionary Methods

Method

Description

dic.clear()

Removes all the elements from the dictionary.

dict.copy()

Returns a copy of the dictionary.

dict.pop()

Removes an element with the specified key.

dict.get()

Returns the value of the specified key.

dict.keys()

Returns a list of keys of the dictionary.

dict.items()

Returns a list with a tuple for each key-value pair.

popItem()

Removes the last added key-value pair.

dict.update(dict2)

Updates the dictionary with key-value pairs.

dict.get(key, default = “None”)

Returns the value specified for the passed key.

dict.setdefault(key,default= “None”)

Sets the key to the default value if it is not specified in the dictionary.

dict.values()

Returns a list of all the values of the dictionary.

dict.has_key(key)

Returns True if the dictionary contains the specified key; else returns False.

In a Python dictionary, keys refer to unique identifiers used to access values, whereas values are data related to those keys.

A dictionary is unordered and mutable that stores Python objects as values. We use it to store key-value pairs.

all() is used to check if all values in a dictionary are True.

any() assesses if a value in a dictionary is True.

cmp() compares two dictionaries, but this method is not available in Python 3.

sorted() returns a new sorted list of keys in a dictionary

We use print() to display all contents of a dictionary. We access keys or values to print the complete dictionary or specific elements.

We declare a dictionary in Python by using key-value pairs enclosed within curly braces {}.

Master Data Analytics Program
Updated - 11 Feb 20251 mins readPublished : 17 Sep 2024

Python Strings: All Methods with Example

Python Type Conversion: Types, Benefits, Examples, More

0%