Introduction to Python Programming Cycle of Python Varibles and Datatypes in Python Input and Output in Python Operators in Python Precedence of Operators in Python Typecasting in Python If Else in Python Loops in Python Break, Continue and Pass in Python Functions in Python Default Arguments and Keyword Arguments in Python Strings in python Lists in Python Tuple in Python Dictionary in Python Sets in Python List Comprehension in Python Unpacking Sequences in Python Higher Order Functions in Python Lambda Functions in Python Sieve of Eratosthenes Algorithm in Python Linear Search in Python Binary Search in Python Selection Sort in Python Bubble Sort in Python Insertion Sort in Python Merge Sort in Python

Dictionary in Python

Jump to specific section:
  1. Create Dictionary
  2. Acessing Value
  3. Dictionary Methods
  4. Iterate Over Dictionary
Dictionary in Python is a data type that is used to store key-value pairs. As we know we have dictionaries in languages like Hindi, where we have any word and its meaning. Here the word is key and its meaning or definition is value. This data structure is very useful as it helps us to map a key with a value. In the dictionary keys are unique.

How to Create Dictionary?

We use braces to create a dictionary. Consider the following code:

# create empty dictionary
dict1 = {}
print(type(dict1))
print(dict1)

print()

# create non-empty dictionary
dict2 = {
    "key1" : "Value1",
    "Key2" : "Value2"
}
print(dict2)
            
Output
<class 'dict'>
{}
                    
{'key1': 'Value1', 'Key2': 'Value2'}
                    

Acessing value in dictionary

In list and tuple we use indexes to access values but in a dictionary, we use keys to get its value.
Syntax:
    Dictionary["key"]
Consider following code for better understanding:

dict1 = {
    "key1" : "Value1",
    "Key2" : "Value2"
}

value = dict1["key1"]
print(value)
Output:
Value1

Dictionary methods:

  1. dictionary.get(key): It returns Value corresponding to given key.
  2. dictionary.items(): It returns an object. Every value of this object is a tuple storing key-value pairs.
  3. dictionary.keys(): It returns a list of keys present in the dictionary.
  4. dictionary.values(): It returns a list of values present in the dictionary.
  5. dictionary.popitem(): It removes last element(key value pair) from dictionary and returns it.
  6. dictionary.pop(key): It removes element(key value pair) from dictionary corresponding to given key.
  7. dictionary.update(dictionary2): It is used to insert all items of dictionary2 in dictionary.
  8. dictionary.clear(): It is used to remove all elements of the dictionary.

Consider following code:

print(f"dict1.items() = { dict1.items() }")
print()
print(f"dict1.keys() = { dict1.keys() }")
print()
print(f"dict1.values() = { dict1.values() }")
print()
print(f"dict1.popitem() = { dict1.popitem() }")
print()
print(f"Updated dict1 : { dict1 }")
print()
dict1.pop("math")
print(f"Updated dict1 after dict1.pop('math') : { dict1 }")
print()

dict2 = {
    "html" : 88,
    "css" : 90
}

dict1.update(dict2)
print(f"Updated dict1 : { dict1 }")
print()

dict1.clear()
print(f"dict1 after performing dict1.clear() : { dict1 }")
Output:
dict1.get('math') = 90

dict1.items() = dict_items([('math', 90), ('python', 100), ('DBMS', 80), ('C++', 95)])

dict1.keys() = dict_keys(['math', 'python', 'DBMS', 'C++'])

dict1.values() = dict_values([90, 100, 80, 95])

dict1.popitem() = ('C++', 95)

Updated dict1 : {'math': 90, 'python': 100, 'DBMS': 80}

Updated dict1 after dict1.pop('math') : {'python': 100, 'DBMS': 80}

Updated dict1 : {'python': 100, 'DBMS': 80, 'html': 88, 'css': 90}

dict1 after performing dict1.clear() : {}

Iterate over dictionary

We can iterate over dictionary using "dictionary.keys()" method or "dictionary.items()" method. Consider the following code:

# consider following dictionary storing subjects and their marks
dict1 = {
    "math" : 90,
    "python" : 100,
    "DBMS" : 80,
    "C++" : 95
}

print("Iterate over dictionary using dictionary.keys()")
for key in dict1.keys():
    print(f"{ key } : { dict1[key] }")
    
print()
print("Iterate over dictionary using dictionary.items()")
for key,value in dict1.items():
    print(f"{ key } : { value }")
Output:
Iterate over dictionary using dictionary.keys()
math : 90
python : 100
DBMS : 80
C++ : 95

Iterate over dictionary using dictionary.items()
math : 90
python : 100
DBMS : 80
C++ : 95