Previous Index Next

Dictionary

A dictionary in Python is an unordered set of key: value pairs. Each KEY must be unique, but the VALUES may be the same for two or more keys. You can use a KEY to locate a specific VALUE in dictionary.

Creating a Dictionary

phonebook = {
    'Deepak':98107593,
    'Saksham':92104584,
    'John':87989898
}

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets:

>>> phonebook = {
	'Deepak':98107593,
	'Saksham':92104584,
	'John':87989898
	}
>>> phone = phonebook['Saksham']
>>> print(phone)
92104584

Using in Operator

To determine if a specified key is present in a dictionary use the in keyword:

Program (dict.py)

phonebook = {'Deepak':98107593, 'Saksham':92104584, 'John':87989898}
if 'Saksham' in phonebook:
    print(phonebook['Saksham'])
else:
    print('Not Found')

Output

92104584

Adding Items

You can add an item to the dictionary by using a new index key and assigning a value to it:

>>> phonebook = {'Deepak':98107593, 'Saksham':92104584, 'John':87989898}
>>> phonebook['Sophia'] = 88939390
>>> print(phonebook)
{'Deepak': 98107593, 'Saksham': 92104584, 'John': 87989898, 'Sophia': 88939390}

Note: You cannot have duplicate keys in a dictionary. When you assign a value to an existing key, the new value replaces the existing value.

>>> phonebook['Saksham'] = 88776655
>>> print(phonebook)
{'Deepak': 98107593, 'Saksham': 88776655, 'John': 87989898, 'Sophia': 88939390}

Deleting Elements

The del keyword removes the item with the specified key name:

>>> phonebook = {'Deepak':98107593, 'Saksham':92104584, 'John':87989898}
>>> del phonebook['Saksham']
>>> phonebook
{'Deepak': 98107593, 'John': 87989898}

Dictionary Length

To get the number of elements in a dictionary you can use the len() method.

>>> phonebook = {'Deepak':98107593, 'Saksham':92104584, 'John':87989898}
>>> n = len(phonebook)
>>> print(n)
3

Empty Dictionary

There are two ways to construct an empty dictionary. You can construct an empty dictionary by having {} with no values in them

>>> d = {}
>>> print(d)
{}

To construct an empty dictionary you can also use the built-in function dict() like this

>>> d = dict()
>>> print(d)
{}

Loop Through a Dictionary

You can loop through a dictionary by using a for loop. The following code segment demonstrates this:

Program (forloop.py)

phonebook = {'Deepak':98107593, 'Saksham':92104584, 'John':87989898}
for key in phonebook:
    print(key,phonebook[key])

Output

Deepak 98107593
Saksham 92104584
John 87989898

Dictionary Methods

Dictionary objects have several methods.

keys()

Returns all the keys in a dictionary as a sequence of tuples.

>>> d = {'X':10, 'Y':20, 'Z':30}
>>> d.keys()
dict_keys(['X', 'Y', 'Z'])

values()

Returns a list of all the values in the dictionary

>>> d = {'X':10, 'Y':20, 'Z':30}
>>> d.values()
dict_values([10, 20, 30])

items()

Returns all the keys in a dictionary and their associated values as a sequence of tuples.

>>> d = {'X':10, 'Y':20, 'Z':30}
>>> d.items()
dict_items([('X', 10), ('Y', 20), ('Z', 30)])

get()

Gets the value associated with a specified key.

>>> d = {'X':10, 'Y':20, 'Z':30}
>>> d.get('Y')
20

pop()

Returns the value associated with a specified key and removes that key-value pair from the dictionary.

>>> d = {'X':10, 'Y':20, 'Z':30}
>>> d.pop('Z')
30
>>> d
{'X': 10, 'Y': 20}

popitem()

Returns a randomly selected key-value pair as a tuple from the dictionary and removes that key-value pair from the dictionary.

>>> d = {'X':10, 'Y':20, 'Z':30}
>>> d.popitem()
('Z', 30)
>>> d
{'X': 10, 'Y': 20}

clear()

Clears the contents of a dictionary.

>>> d = {'X':10, 'Y':20, 'Z':30}
>>> d.clear()
>>> d
{}

copy()

Returns a copy of the dictionary

>>> d = {'X':10, 'Y':20, 'Z':30}
>>> x = d.copy()
>>> x
{'X': 10, 'Y': 20, 'Z': 30}

update()

Updates the dictionary with the specified key-value pairs

>>> d = {'A':10, 'B':20, 'C':30}
>>> d.update({'B':25})
>>> d
{'A':10, 'B':25, 'C':30}
>>> d = {'X':10, 'Y':20, 'Z':30}
>>> d.update({'W':40})
>>> d
{'X': 10, 'Y': 20, 'Z': 30, 'W': 40}

setdefault()

Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

>>> d = {'X':10, 'Y':20, 'Z':30}
>>> d.setdefault('Y',88)
20
>>> d
{'X': 10, 'Y': 20, 'Z': 30}
>>> d = {'A':100, 'B':200}
>>> d.setdefault('C',300)
300
>>> d
{'A': 100, 'B': 200, 'C': 300}

fromkeys()

Returns a dictionary with the specified keys and value.

>>> x = ('k1', 'k2', 'k3')
>>> y = dict.fromkeys(x,0)
>>> print(y)
{'k1': 0, 'k2': 0, 'k3': 0}

Previous Index Next