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

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

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

name = 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 it, and all the elements are separated by a comma.

# Empty
a = {}
a = dict()

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

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

d = {'name': 'TutorialGateway', 'age': 25}
e = {'name': 'TutorialGateway', 1: 22}
f = {'name': 'TutorialGateway', 1: [1, 2, 3]}


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

h = 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, the get function with return none. Whereas placing the key inside a square brackets method throw an error

Dname[key] or Dname.get(key)

# Access Items Example

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

# Print 
print(a)

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

# using get()
print("\nItems - Name  :  ",  a.get('name'))
print("Items - Age   :  ",  a.get('age'))
print("Items - Job   :  ",  a.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.

DName[key] = value

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

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

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

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

# Update an Item
dat['name'] = 'Python'
print("\nItems  :  ",  da)
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(fruits)
print("Length: ", len(fruits))

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

{'a': 'apple', 'o': 'Orange', 'm': 'Mango', 'k': 'Kiwi'}
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).

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

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

# Remove and Prints Item using popitem()
print("\nRemoved Item      :  ",  db.popitem())
print("Remaining Items  :  ",  db)
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 values at a specified key. If we miss providing it, then the compiler completely deletes or removes them. Here, the last statement is raising an error.

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

print("Items are = ", dm)

# Remove Item using del
del dm[2]
print("Items are = ", dm)

# Remove All Items using del
del dm
print("Items are = ", dm)
Python Dictionary 4

The clear statement removes or clears the items and returns curly braces.

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

# Remove all Items using clear()
dc.clear()
print("Items  :  ",  dc)
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.

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

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

For loop to Print Values

The for loop iterate and print the values inside it.

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

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

This example prints the Keys and Values.

de = {1: 'apple', 2: 'Berry' , 3: 'Orange', 4: 'Kiwi', 5: 'Cherry'}

for val in de:
    print(val, "Key Value = ", de[val])
1 Key Value =  apple
2 Key Value =  Berry
3 Key Value =  Orange
4 Key Value =  Kiwi
5 Key Value =  Cherry

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

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

for i in df.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.

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

for i, j in dg.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.
  • pop() remove and print the item of a given key. Use to delete.
  • 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.

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

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

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

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

key_total = sum(da.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.

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

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

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

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

max_key = max(da.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