Table of Contents


A dictionary is a collection of data elements. Data is indexed, but here the index is a string name for each element and not their order number like in lists. These strings are known as keys. Only strings are accepted as keys. However, data elements can be any object, for example strings, list or tuples. A dictionary can contain any object, includong other dictionaries or lists which build a nested dictionary.

Dictionaries are not ordered in the sequence of their creation, they have no particular order as they are indexed by the keys. Keys can be sorted and searched or filtered. Each element in a dictionary is made of key-value pair. Values can be changed and modified. Changing the key means creating a new key-value pair. In Python dictionaries are written with curly brackets {}.

Creating dictionary

Dictionaries can be built in various ways.

To build an empty Dictionary use using empty curly brackets or dict() functions. You can later add key-value pairs one by one. d = {} => d is an empty dictionary d[key] = value => we add the value and key to the created dictionary

Mapping Objects

The dict() function allows mapping of any object with key-value pairs into a dictionary. For example. a nested list of lists, in which each list is a pair of key-value. nl = [["key1", 100], ["key2", 200]] => this is a nested list of two lists made of pair of values dict(nl) => {'key1': 100, 'key2': 200} => now dict() function converted nl into a dictionary


Dictionaries can be built from a list of tuples, each containing pairs of strings or string-value pairs. The list is used as an argument for the dict() function. dict([("a", "first"),("b", "second"),("c", "third")])


A comma separated nested strings of couplets joined by separator such as dash -\ can used as an argument for dict() function. The string is made of a sequence of couplet strings joined by separator and each couplet separated from other by comma. Such string will be converted to nested list by split each couplet in the long string. string = ' "a" - 100, "b" - 200 ' dict(e.split(' - ') for e in string.split(',')) => split string into list then each element is split by dash

Lists and Indices

Any list of strings can be converted to a dictionary if we accept to use numerical indices as keys for the created dictionary. Here we use the enumerate(list) function.

    list = [ "a" , 100, "b" , 200 ]
    dict(enumerate(list)) => {0: 'a', 1: 100, 2: 'b', 3: 200}

Single List

Even a single list of key followed by value in sequence can be used as an argument for dict() function. list = [ "a" , 100, "b" , 200 ] dict(zip([iter(list)]2))

Keyword Arguments

It is possible to create a list by entering a sequence of keyword arguments "key=value" to the dict() function. In this way, you avoid adding quotes to each key entered in the dictionary. Values in those keyword arguments should be quoted if they are strings.

  dict(sape=4139, guido=4127, jack=4098)   => {'sape': 4139, 'jack': 4098, 'guido': 4127}

Dictionary Comprehension

Like list comprehension, you can create dictionaries by dict comprehensions, as in this example :

    {x: x**2 for x in (2, 4, 6)} => {2: 4, 4: 16, 6: 36}

Nested Lists

A nested list of lists each of a key-value pair of elements can be converted into a dicitonary:

    lst = [["a", 100],["b", 200]]
    dict(lst) => {'a': 100, 'b': 200}
    music = [
     ["Blind Melon", "No Rain"],
     ["Damian Marty", "Ji Gong"]
    dict(music) => {'Blind Melon': 'No Rain', 'Damian Marty': 'Ji Gong'}

2 Parallel Lists

If you have two lists, the first for the keys and the second for the values, you may be able to create a dictionary using zip() function which combines each element in the first list with the corresponding element in the second list while building a nested list of all elements of both lists.

    names = ["Nick", "Alice", "Kitty"]
    professions = ["Programmer", "Engineer", "Art Therapist"]
    dict(zip(names, professions)) ##>{'Nick': 'Programmer', 'Alice': 'Engineer', 'Kitty': 'Art Therapist'}

Mapping Iterables

Dict() function can create a dictionary (This is known as mapping) from any iterable of sequence of pairs. For example, a nested list of pairs as above.

    d = {}
    for k, v in iterable:
        d[k] = v

Searching a dictionary

Searching for a specific key

To search a dictionary key, use the simple keyword "IN".

h = { "d" : 100, "a" : 200, "v" : 300, "e" : 400 } "d" in h True "200" in h False

You may also use the contains() function: D.contains(key) This returns True if the dictionary has the specified key, else False.

Searching for a specific valeu ###

To search a dictionary for a value, if you know the key use the key to get that value.

dict[key] => value

If you do not know the key, and want to search all the values, you have to iterate over all the values to get the desired key-value pair.

searching for a key or a value in a dictionary

h = { 1 : "a", 2 : "b", 3 : "c" } for k,v in h.items(): if v == "b" : print(k,v)

If you do not know the value you are searching for, but know something about it, you may use conditional search or regex pattern.

For example you know that the value is within a range of values, more or less than a figure.

h = { "Adam" : 100, "Bell" : 100, "Diane" : 300, "Jerry" : 200, "Fiona" : 50 } [(k, v) for k, v in h.items() if v > 100] => [('Diane', 300), ('Jerry', 200)]

This will get you more than one key-value pairs matching your criteria in the form of a list of tuples. The if statement may contain any condition such as re.match(pattern, value), value.startswith(pattern). etc.

View dictionary contents

You may need to have an idea about the dictionary in general, like its size and number of items or list of its keys.

Number of items in a dictionary

To get the number of key-value pairs in dict use len keyword :

h = { "d" : 100, "a" : 200, "v" : 300, "e" : 400 } len(h)

Get all Keys or all Values

Functions D.keys() get an object containing a list of keys. To get the keys in the form of a list, use the list function: (D.keys())

h = { "d" : 100, "a" : 200, "v" : 300, "e" : 400 } list(h.keys())

The same is true with values, the D.values() function return an object containing values:

h = { "d" : 100, "a" : 200, "v" : 300, "e" : 400 } list(h.values()) [100, 200, 300, 400]

D.items() gets you a list of tuples containing each key and value in a tuple.

h = { "d" : 100, "a" : 200, "v" : 300, "e" : 400 } list(h.items()) [('d', 100), ('a', 200), ('v', 300), ('e', 400)]

Extract Data from Dictionary

GET or D[key]

To get the value of a key use D[key] expression. This is the same as the get() function : D.get(key)

h = { "d" : 100, "a" : 200, "v" : 300, "e" : 400 } h["v"] h.get("v")

POP the value of the key

The pop function returns the value of the key and remove it. It has the advantage of returning a message if the key is not found:

D = {'sape': 4139, 'jack': 4098, 'guido': 4127} r = D.pop('sape') => get the value in sape and remove the pair. r => 4139 D => {'jack': 4098, 'guido': 4127} => now dictionary is missing sape pair. D.pop('john', "No such key")

D.popitem() returns both the key and value in a tuple.


You may wish to iterate over dictionary items one by one similar to lists, though you need two variables for key and value. The items() function get you all the dictionary into a list of tuples which you iterate over them one by one:

knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in knights.items(): print( k, v)

Update the data in a Dictionary

You may update data in a dictionary by adding a new key-value pair item, remove a key-value pair or modify the value of a given item. Sometimes, you may need to delete the whole dictionary or combine it with another.

Adding Items to a dictionary

You add an item to a dictionary by giving a NEW key and its value.

D[key] = value 

If the key is already in the dictionary, you will be actually modifying its value. So, if not sure, check if key exist, for example :

D = {2: 4, 4: 16, 6: 36} if 8 not in D: D[8] = 72 D => {2: 4, 4: 16, 6: 36, 8: 72}

Change a Key name

There are two ways to change key names, create a new key with value of key to be changed, then delete the old key.

h = { "a" : 100, "b" : 200 } h["alpha"] = h["a"] => here "alpha" pair gets the value of the "a" pair
del h["a"] => then we delete the "a" pair h

The other way is using the pop() function, you remove the value of that key and give it to the new key.

h = { "a" : 100, "b" : 200 } h["alpha"] = h.pop("a") => the "a" value is given to the "alpha" key and deleted at one step h

How to Change a value in a dictionary

If you have the key name, it is as easy as giving it a new value.

D[old_value] = new_value

Delete a dictionary item

The del keyword deletes the key-value pair from a dictionary

tel = {'jack': 4098, 'sape': 4139} del tel['sape'] tel

Remove all data from a dictionary

h = { "a": 100, "b" : 200 } h.clear() tel

Working with more than one dictionary

How to merge Two Dictionaries

The Update function merges two dictionaries and remove duplicates.

h1 = { "a" : 100, "b" : 200 } h2 = { "b" : 254, "c" : 300 } h1.update(h2) h1 =value of duplicate key from the second dictionary is used instead.

How to substitute contents of dictionary with another

Here you are actually writing a new dictionary into the same memory data slot of the first one.

h = { "a" : 100, "b" : 200 } h = { "c" : 300, "d" : 400 } h

Working with Nested Dictionaries

A Dictionary can have another sub-dictionary or a list as value for one of its keys. A large dictionary can have many sub-dictionaries as values for each of its primary keys.

This is the basis of Data Interchange format of JSON. Searching a nested dictionary is done through going down consecutive keys in the hierarchy to the required key-value pair. i.e. triggering the search with the formula : Dictionary[top][Mid][Down][target_key]

To get value in nested dictionaries:

player = { 'babe' : { 'hits' : 2873, 'home_runs' : 714, 'ops' : 474 }, 'barry' : { 'hits' : 2935, 'home_runs' : 762, 'ops' : 444 } } players['babe']['home_runs'] => 714

Importing a Dictionary from CSV file

Dictionary is a data container which has very fast access time. It can be searched and updated much faster than list as a mutable object.

This makes it suitable to store and retrieve data. Data can be stored in a file on the hard disk and transferred to a dictionary during script processing. Comma separated files are simple text files where data is organised in rows with or without headings in first row.

They can be converted into a dictionary using csv module.

import csv reader = csv.reader(open("test.csv", 'r')) d = {} for row in reader: k, v = row d[k] = v d