Python Dictionary

A Python Dictionary is a collection which is unordered, changeable, and indexed. Unlike a string, the Dictionary is mutable. So, the Python dictionary can expand or sink.

Python Dictionary Syntax

We can declare a Python Dictionary by simply placing empty parenthesis, or using the dict(). The syntax for declaring a dictionary in Python

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

Or you can use python dict keyword to create a Dictionary.

myDict = dict([
    (<key>:<value>),
    (<key>:<value>),
    .
    .
    .
    (<key>:<value>)
    ])

How to create a Python Dictionary?

The list of available ways to declare or create a dictionary in Python programming.

# Python Dictionary

# Empty Dictionary
myDict = {}
myDict = dict()

# Dictionary with Integer Keys
myDict = {1: 'apple', 2: 'Orange', 3: 'Kiwi'}

# Dictionary with String Keys
myDict = {'fruit': 'apple', 'name': 'Kevin'}

# Dictionary with Mixed Keys
myDict = {'name': 'TutorialGateway', 'age': 25}
myDict = {'name': 'TutorialGateway', 1: 22}
myDict = {'name': 'TutorialGateway', 1: [1, 2, 3]}

# Python Dictionary using dict()

# For Sequence of Key-Value Pairs
myDict = dict([(1, 'apple'), (2, 'Orange'), (3, 'Kiwi')])

# For Simple Keys
myDict = dict({1: 'apple', 2: 'Orange', 3: 'Kiwi'})

How to Access Python Dictionary items?

We can access the Dictionary values using their keys. It can be done by placing the key in the square brackets or using get function. If we access non-existing key, Python get function with return none. Whereas placing the key inside a square brackets method throw an error

Dictionary_name[key] or Dictionary_name.get(key)

# Python Dictionary Example

myDict = {'name': 'Kevin', 'age': 25, 'job': 'Developer'}

# Print Total Dictionary
print("Dictionary Items  :  ",  myDict)

# Print Values using Dictionary Keys
print("\nDictionary Key - Name :  ",  myDict['name'])
print("Dictionary Key - Age  :  ",  myDict['age'])
print("Dictionary Key - Job  :  ",  myDict['job'])

# Dictionary Values using get()
print("\nDictionary Items - Name  :  ",  myDict.get('name'))
print("Dictionary Items - Age   :  ",  myDict.get('age'))
print("Dictionary Items - Job   :  ",  myDict.get('job'))

Accessing Dictionary items output

Dictionary Items : {'name': 'Kevin', 'age': 25, 'job': 'Developer'}

Dictionary Key - Name : Kevin
Dictionary Key - Age : 25
Dictionary Key - Job : Developer

Dictionary Items - Name : Kevin
Dictionary Items - Age : 25
Dictionary Items - Job : Developer

Insert and Update Dictionary items in Python

Remember, dictionaries are mutable so, you can insert or update any value at any point in time. Use below dictionary syntax to insert or update values.

Dictionary_name[key] = value

If a key is present, it updates the key value. If Dictionary_name does not have the key, then it inserts the new key with a given value.

# Python Dictionary Example

myDict = {'name': 'Kevin', 'age': 25}

# Print Total Dictionary
print("Dictionary Items  :  ",  myDict)

# Add an Item to Dictionary
myDict['job'] = 'Programmer'
print("\nDictionary Items  :  ",  myDict)

# Update an Item in Dictionary
myDict['name'] = 'Python'
print("\nDictionary Items  :  ",  myDict)
Dictionary Items : {'name': 'Kevin', 'age': 25}
Dictionary Items : {'name': 'Kevin', 'age': 25, 'job': 'Programmer'}
Dictionary Items : {'name': 'Python', 'age': 25, 'job': 'Programmer'}

How to copy the Dictionary Items?

The copy functions shallow copy the given dictionary into a completely new one. You can also place a Dictionary inside a list.

# Python Dictionary copy Example

fruits = {'a': 'apple', 'o': 'Orange', 'm': 'Mango', 'k':'Kiwi'}

print("Dictionary: ", fruits)
print("Dictionary Length: ", len(fruits))

new_fruits = fruits.copy()
print("\nDictionary: ", new_fruits)
print("Dictionary Length: ", len(new_fruits))
Dictionary: {'a': 'apple', 'o': 'Orange', 'm': 'Mango', 'k': 'Kiwi'}
Dictionary Length: 4

Dictionary: {'a': 'apple', 'o': 'Orange', 'm': 'Mango', 'k': 'Kiwi'}
Dictionary Length: 4

Remove Python Dictionary items

There are several ways to delete dictionary items. The Dictionary pop method removes the value at a given key, and prints the removed value. The Python popitem removes the last inserted item (key, value pair).

# Python Dictionary Example

myDict = {1: 'apple', 2: 'Orange', 3: 'Kiwi', 4: 'Banana'}

# Remove and Prints Item of a Dictionary Key using pop()
print("Removed Item      :  ",  myDict.pop(3))
print("Dictionary Items  :  ",  myDict)

# Remove and Prints Item of a Dictionary Key using popitem()
print("\nRemoved Item      :  ",  myDict.popitem())
print("Dictionary Items  :  ",  myDict)
Removed Item : Kiwi
Dictionary Items : {1: 'apple', 2: 'Orange', 4: 'Banana'}

Removed Item : (4, 'Banana')
Dictionary Items : {1: 'apple', 2: 'Orange'}

The del statement removes the Python dictionary items or value at a specified key. If we miss providing the key, it completely deletes or removes.

# Python Dictionary Example

myDict = {1: 'apple', 2: 'Orange', 3: 'Kiwi', 4: 'Banana'}

print("Dictionary Items  :  ",  myDict)

# Remove Item of a Dictionary Key using del
del myDict[2]
print("Dictionary Items  :  ",  myDict)

# Remove all Items from Dictionary using del
del myDict
print("Dictionary Items  :  ",  myDict)
Python Dictionary 4

The Python dictionary clear statement removes or clears the items.

# Python Dictionary Example

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Dictionary Items  :  ",  myDict)

# Remove all Items from Dictionary using clear()
myDict.clear()
print("Dictionary Items  :  ",  myDict)
Dictionary Items  :   {1: 'apple', 2: 'Banana', 3: 'Orange', 4: 'Kiwi'}
Dictionary Items  :   {}

Python Dictionary Iterate items

The For Loop is the most common way to traverse or iterate python dictionary items.

For loop to Print Dictionary Keys

The for loop help us to iterate and print the dictionary keys.

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}

# Print Dictionary Keys
for value in myDict:
    print(value)

Printing the Dictionary keys

1
2
3
4

For loop to Print Dictionary Values

The for loop iterate and print the values inside a dictionary.

# Python Dictionary Example

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}

# Print Dictionary Values
for value in myDict:
    print(myDict[value])

Printing the dictionary values

apple
Banana
Orange
Kiwi

This example prints Dictionary Keys and Values

# Python Dictionary Example

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}

# Print Dictionary Values
for value in myDict:
    print(value, "Key Value = ", myDict[value])
Python Dictionary 8

The values function is helpful to print the Python dictionary values. Use this dictionary values function inside the for loop to return values.

# Python Dictionary Example

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}

# Print Dictionary Values
for i in myDict.values():
    print(i)
apple
Banana
Orange
Kiwi

items function to Print Dictionary keys, and Values

You can use the dictionary items function inside the for loop to return dictionary keys and values. The dictionary items function is very useful to access individual items.

# Python Dictionary Example

myDict = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}

# Print Dictionary Values
for i, j in myDict.items():
    print(i, j)
1 apple
2 Banana
3 Orange
4 Kiwi

Python Dictionary Methods

Python Dictionary provides the following methods

  1. clear() – Removes all items.
  2. copy() – Shallow copy.
  3. fromkeys() – Returns a new dictionary, where keys start from a sequence and values equal to values.
  4. get() – Value of a Given Key.
  5. items() – Returns a list containing the dictionary items (key, value pairs)
  6. keys() – Prints a list of keys
  7. pop() – Remove and prints the value of a given key.
  8. popitem() – Remove and prints the last inserted key-value pair. 
  9. setdefault() – If the given key is present, it returns its value. If not, this function insert key with a given value, and prints that value.
  10. update() – Update the Key-Value pair.
  11. values() – Returns the list of all the values.

Common Python Dictionary Methods

The common methods that can use on Lists, Dictionaries, Tuples. The following examples help you understand those common dictionary methods.

The Dictionary len function finds the sum of all available items.

# Python Dictionary len Example

myDict = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
print("Dictionary: ", myDict)

# Dictionary length using len() 
length = len(myDict)
print("The Length of a Dictionary : ", length)

myDict2 = {'name': 'Kevin', 'age': 25}
print("\nDictionary: ", myDict2)
print("The Length of a Dictionary : ", len(myDict2))
Dictionary: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
The Length of a Dictionary : 5

Dictionary: {'name': 'Kevin', 'age': 25}
The Length of a Dictionary : 2

The Dictionary sum function finds the sum of all items.

myDict = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
print("Dictionary: ", myDict)

# Sum of Dictionary Items using dictionary sum() 
total = sum(myDict.values())
print("\nThe sum of Values in this Dictionary : ", total)

key_total = sum(myDict.keys())
print("The sum of Keys in this Dictionary  : ", key_total)
Dictionary: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}

The sum of Values in this Dictionary : 150
The sum of Keys in this Dictionary : 15

Dictionary min function finds the minimum value.

# Python Dictionary min Example

myDict = {3: 30, 4: 40, 1: 120, 2: 20, 5: 50}
print("Dictionary: ", myDict)

# Minimum Dictionary Items using dictionary min() 
min_value = min(myDict.values())
print("\nThe Minimum Value in this Dictionary : ", min_value)

min_key = min(myDict.keys())
print("The Minimum Key in this Dictionary  : ", min_key)
Dictionary: {3: 30, 4: 40, 1: 120, 2: 20, 5: 50}

The Minimum Value in this Dictionary : 20
The Minimum Key in this Dictionary : 1

The Dictionary max function finds the maximum value.

# Python Dictionary max Example

myDict = {3: 30, 4: 40, 1: 120, 2: 20, 5: 50}
print("Dictionary: ", myDict)

# Maximum Dictionary Items using dictionary max() 
max_value = max(myDict.values())
print("\nThe Maximum Value in this Dictionary : ", max_value)

max_key = max(myDict.keys())
print("The Maximum Key in this Dictionary  : ", max_key)
Dictionary: {3: 30, 4: 40, 1: 120, 2: 20, 5: 50}

The Maximum Value in this Dictionary : 120
The Maximum Key in this Dictionary : 5