Python Dictionary

A Python Dictionary is a collection which is unordered, changeable, and indexed. Unlike a string, it is mutable. So, the Python dict 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

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

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

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

How to create a Python Dictionary?

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

We can use the curly braces to create a dictionary, and all the elements are separated by a comma.

# Empty
myDict1 = {}
myDict1 = dict()

# Integer
myDict2 = {1: 'apple', 2: 'Orange', 3: 'Kiwi'}

# String
myDict3 = {'fruit': 'apple', 'name': 'Kevin'}

myDict4 = {'name': 'TutorialGateway', 'age': 25}
myDict5 = {'name': 'TutorialGateway', 1: 22}
myDict6 = {'name': 'TutorialGateway', 1: [1, 2, 3]}

# using dict()

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

myDict8 = dict({1: 'apple', 2: 'Orange', 3: 'Kiwi'})

How to Access Python Dictionary items?

Though, dictionary is an unordered collection, we can access the 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 one, 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)

# Access Items Example

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

# Print 
print(myDict)

print("\nName :  ",  myDict['name'])
print("Age  :  ",  myDict['age'])
print("Job  :  ",  myDict['job'])

# using get()
print("\nItems - Name  :  ",  myDict.get('name'))
print("Items - Age   :  ",  myDict.get('age'))
print("Items - Job   :  ",  myDict.get('job'))
{'name': 'Kevin', 'age': 25, 'job': 'Developer'}

Name : Kevin
Age : 25
Job : Developer

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

Insert and Update Python Dictionary items

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

DictionaryName[key] = value

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

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

# Print Elements
print("Items  :  ",  myDict)

# Add an Item
myDict['job'] = 'Programmer'
print("\nItems  :  ",  myDict)

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

How to copy the Dictionary Items?

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

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

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

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

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

Remove Python Dictionary items

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

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

# Remove and Prints Item using pop()
print("Removed Item      :  ",  myDict.pop(3))
print("Remaining Items  :  ",  myDict)

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

Removed Item : (4, 'Banana')
Remaining 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. Here, the last statement is raising error.

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 clear statement removes or clears the items and returns curly braces.

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

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

Python Dictionary Iterate items

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

For loop to Print Keys

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

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

for val in myDict:
    print(val)
1
2
3
4

For loop to Print Values

The for loop iterate and print the values inside it.

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

for val in myDict:
    print(myDict[val])
apple
Banana
Orange
Kiwi

This example prints Keys and Values

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

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

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

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

for i in myDict.values():
    print(i)
apple
Banana
Orange
Kiwi

items function

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

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

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

Python Dictionary Methods

It provides the following built-in functions or methods

  • clear() removes all the elements.
  • copy() shallow copy.
  • fromkeys() returns a new one, where keys start from a sequence and equal to values.
  • get() value of a Given Key.
  • items() returns a list containing the items (keyvalue pairs)
  • keys() Prints a list of keys in a dict.
  • pop() remove and print the item of a given key. Use to delete a dict key.
  • popitem() removes and prints the last inserted keyvalue pair. 
  • setdefault() – If the given key is present, it returns its value. If not, this function inserts a key with a given value and prints that.
  • update() updates the KeyValue pair.
  • 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 methods.

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

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

length = len(myDict)
print("The Length: ", length)
print()

myDict2 = {'name': 'Kevin', 'age': 25}
print(myDict2)
print("The Length: ", len(myDict2))

total = sum(myDict.values())
print("\nThe sum of Values: ", total)

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

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

The sum of Values: 150
The sum of Keys: 15

Python dict min function finds the minimum value. The max function finds the maximum element.

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

min_value = min(myDict.values())
print("\nThe Minimum Val: ", min_value)

min_key = min(myDict.keys())
print("The Minimum Ky: ", min_key)

max_value = max(myDict.values())
print("\nThe Maximum Val: ", max_value)

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

The Minimum Val: 20
The Minimum Ky: 1

The Maximum Val: 120
The Maximum Ky: 5