python

Dictionary Datatype


It is a collection of homogenous and heterogeneous items. Items are nothing but Key - Value pair, enclosed with { } boundary.

  • It is mutable type data.
  • It is ordered with keys but can't be indexed or sliced.
  • We can measure length of the dictionary using len function. Len function returns total number of keys only.
  • In dictionary datatype, only key layer is visible to the interpreter. Hence, without key reference we cannot operate dictionaries.
  • Characteristics of keys are similar to set type of keys.
  • Characteristics of elements are similar to list elements.

 

Creating dictionaries

You can create a dictionary by placing a comma-separated sequence of key-value pairs within curly braces {}, with a colon : separating each key from its value.

Examples:

# Creating an empty dictionary
empty_dict = {}
# Creating a dictionary with integer keys
int_keys_dict = {1: 'apple', 2: 'banana'}
# Creating a dictionary with mixed keys
mixed_keys_dict = {'name': 'John', 1: [2, 4, 3]}
# Creating a dictionary using the dict() function
dict_using_func = dict({1: 'apple', 2: 'banana'})
# Creating a dictionary from a list of tuples
dict_from_tuples = dict([(1, 'apple'), (2, 'banana')])
 

 

Accessing Dictionary Elements

You can access dictionary elements by their key. If the key is not present in the dictionary, it will raise a KeyError.

Examples:

dict_example = {'name': 'John', 'age': 25, 'city': 'New York'}
# Accessing elements
print(dict_example['name'])  # Output: John
print(dict_example['age'])   # Output: 25
# Using the get() method to access elements
print(dict_example.get('city'))      # Output: New York
print(dict_example.get('country'))   # Output: None (default value if key is not found)
print(dict_example.get('country', 'USA')) # Output: USA (default value if key is not found)
 

 

Adding and Modifying Dictionary Elements

You can add new elements to a dictionary or modify existing elements by assigning a value to a key.

Examples:

dict_example = {'name': 'John', 'age': 25, 'city': 'New York'}
# Adding a new key-value pair
dict_example['country'] = 'USA'
print(dict_example)  # Output: {'name': 'John', 'age': 25, 'city': 'New York', 'country': 'USA'}
# Modifying an existing key-value pair
dict_example['age'] = 26
print(dict_example)  # Output: {'name': 'John', 'age': 26, 'city': 'New York', 'country': 'USA'}
 

 

Removing Dictionary Elements

You can remove elements from a dictionary using the del statement, the pop() method, or the popitem() method.

Examples:

dict_example = {'name': 'John', 'age': 25, 'city': 'New York', 'country': 'USA'}
# Using the del statement
del dict_example['city']
print(dict_example)  # Output: {'name': 'John', 'age': 25, 'country': 'USA'}
# Using the pop() method
age = dict_example.pop('age')
print(age)           # Output: 25
print(dict_example)  # Output: {'name': 'John', 'country': 'USA'}
# Using the popitem() method (removes the last inserted key-value pair)
item = dict_example.popitem()
print(item)          # Output: ('country', 'USA')
print(dict_example)  # Output: {'name': 'John'}
# Clearing all elements from the dictionary
dict_example.clear()
print(dict_example)  # Output: {}
 

 

Dictionary Methods

Python dictionaries come with several built-in methods.

Examples:

dict_example = {'name': 'John', 'age': 25, 'city': 'New York'}
# keys() method: Returns a view object that displays a list of all the keys
keys = dict_example.keys()
print(keys)  # Output: dict_keys(['name', 'age', 'city'])
# values() method: Returns a view object that displays a list of all the values
values = dict_example.values()
print(values)  # Output: dict_values(['John', 25, 'New York'])
# items() method: Returns a view object that displays a list of all the key-value pairs
items = dict_example.items()
print(items)  # Output: dict_items([('name', 'John'), ('age', 25), ('city', 'New York')])
# update() method: Updates the dictionary with the elements from another dictionary or from an iterable of key-value pairs
dict_example.update({'country': 'USA', 'age': 26})
print(dict_example)  # Output: {'name': 'John', 'age': 26, 'city': 'New York', 'country': 'USA'}
# setdefault() method: Returns the value of a key if it is in the dictionary; if not, inserts the key with a specified value
value = dict_example.setdefault('gender', 'male')
print(value)  # Output: male
print(dict_example)  # Output: {'name': 'John', 'age': 26, 'city': 'New York', 'country': 'USA', 'gender': 'male'}
 

python