1. Home
  2. Docs
  3. Python 101 – Python Programming for Beginners
  4. Dictionary

Dictionary

 

Dictionary is a mapping type in Python.

It maps a key to a value,

Dictionaries are mutable and resize-able.

 

In Python currently this is the only  built-in mapping type.

Like other containers in Python (list,tuple)

Dictionaries are heterogeneous, can contain different types of objects.

As dictionaries are mutable, you can add, modify, remove and find an elements from dictionary.

 

Unlike other sequences dictionaries are un-ordered.

 

Creating dictionary.

 
 
A Dictionary can be created using { } curly brackets,
 
or with built-in dict() type constructor.
 
An empty dictionary can be created as below.

 

dict1 = {}

dict2 = dict()


dict1 = {}

dict2 = dict()

dict1

output:

{}

dict2

output:

{}

 
 

this is shows both {} and dict() produce same result.

 
dict1 and dict2 are two empty dictionaries.
 
 

Key value pair of a dictionary

 

book_info = {'title': "Python Programming"}

 
 

In above example, book_info is a reference to a dictionary.
 

with ‘title’ as key and ‘Python Programming’ as its mapped value.

 

Notice while creating a dict we are using { } curly brackets,
 

a ‘ : ‘ colon is used to associate key and value.

 

Keys of dictionary must be an immutable object.
 

Example, keys can be Number, String, tuple etc
 
Ex1.

dict with number as a key

 

place_holder = {1:0,2:10,3:100,4:1000,5:10000}

place_holder[1]

place_holder[4]

  

Ex 2.
 

dictionary with string as a key

 

book_info = {'title': "Python Programming"}

#accessing the created dictionary

book_info

{'title': 'Python Programming'}


  

Ex 3.
 

dict with tuple as a key

  


tuple_key_dict = {(1,2,3):"one two three"}

tuple_key_dict


  

A dict can have list, tuple, dictionary or any other valid Python object as values.
 

List as dictionary value

  

dict_list_values = {"lang":["Python", "C++","Ruby","Java"]}

print(dict_list_values)

output:

{'lang': ['Python', 'C++', 'Ruby', 'Java']}

  

Accessing list values from a dictionary

  

You can also access individual elements of list form dict.

Like a 2 dimensional array. first is dictionary key, and second is index of list.
 

dict_list_values["lang"][0]


dict_list_values["lang"][1]

dict_list_values["lang"][2]


dict_list_values["lang"][3]


output:

Python

C++

Ruby

Java


 

Tuple as dictionary value

  


dict_tuple_values = {"lang":("Python,", "C++","Ruby","Java")}

print(dict_tuple_values)

output:

{'lang': ('Python,', 'C++', 'Ruby', 'Java')}

 

 

Values of tuples inside a dictionary can be accessed

as 2 dimensional array as shown in the list example.

 

dictionary as dictionary value

  


dict_dict_values = {"prog":{"lang":"Python C++ Java"}}

print(dict_dict_values)

output:

{'prog': {'lang': 'Python C++ Java'}}


  

Accessing the dictionary value inside a dictionary

  

dict_dict_values['prog']['lang']


output:

'Python C++ Java'

 

Another example of dictionary inside a dictionary.

  

books = {'book1':{'title':'Python Programming',
                   'published':2018,
                   'category':'technical',
                    'price':200}
         }


print(books)

output:

{'book1': {'title': 'Python Programming', 'published': 2018, 
 
'category': 'technical', 'price': 200}
}

 

 

Accessing inside dictionary values, as 2 dimensional array.
 

  

print(books['book1']['title'])

print(books['book1']['published'])

print(books['book1']['category'])

print(books['book1']['price'])


output:

Python Programming

2018

technical

200

 

 

Using built-in dict() constructor function.

  

We can also create dictionary using built-in constructor or factory function dict().

Notice below, we are using ‘( )’ round brackets instead of {} curly brackets,

and using ‘=’ assignment operator instead of ‘:’ colon

 

Syntax:
 

dict(variable = value)

 
When creating dictionary with dict(), the key must be a string,

and it must be valid variable name.
 

book_info_1 = dict(title = ‘Python Programming’)

 

You can not use numbers as keys, while using dict() function.
 
In this example key is number, Python throws syntax error.
  

Ex 1.
 
Here the key is a number
 

book_info_1 = dict(1 = 'Python Programming')


 File "<ipython-input-23-56cf52e30350>", line 1

    book_info_1 = dict(1 = 'Python Programming')
                      ^
SyntaxError: keyword can't be an expression

 
Ex 2.
 
Here the key ‘1title’ is not a valid variable name
 

book_info_1 = dict(1title = 'Python Programming')


 File "<ipython-input-24-9d773bb605e0>", line 1
    book_info_1 = dict(1title = 'Python Programming')
                            ^
SyntaxError: invalid syntax


  

Dictionaries are like lists, except that they use keys
 
instead of numbers as indexes to look up values.
 
Values of a dictionary, can be accessed by using key as index.

  

Accessing element from dictionary

  


book_info['title']

Python Programming'

  
A dictionary can contain many key-value pairs.
 
Each key-value pair is separated by a  ‘,’ comma.
 
Lets look at an example.

 

Here are creating a dict by using { } curly brackets.
  

dict_number = {'one' : 1, 'two': 2, 'three': 3, 'four':4}

#accessing  the complete dictionary

dict_number

{'one': 1, 'two': 2, 'three': 3, 'four': 4}

 
 

Now let’s try the above example with dict() constructor
  


dict_number1 = dict(one = 1, two =2, three = 3, four = 4)

#access the dictionary

dict_number1

{'one': 1, 'two': 2, 'three': 3, 'four': 4}

 

Adding new elements to dictinary

 
You can add new values to dictionary, by using assignment operator.

if the key is already exists, it overwrites the value,

otherwise adds new key value pair.

 


dict_number1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4}

dict_number1['file'] = 5

dict_number1


output:

{'file': 5, 'four': 4, 'one': 1, 'three': 3, 'two': 2}


  

Notice new element ‘file’: 5 is added to dict_number1.

You can also use update method of dictionary,

 


dict_number1.update({'six': 6})

dict_number1

output:
{'file': 5, 'four': 4, 'one': 1, 'six': 6, 'three': 3, 'two': 2}

 
New element ‘six’: 6 is added to dict_number1.
 
Another use of update function is explained below.

  

Using list of key-value as tuple to create dictionary.

 

We can also use tuple to create a dictionary.

A tuple is passed as list to dict() constructor function.

Key-value pairs are passed as tuple.

 

 


dict_number2 = dict( [('one',1), ('two',2),('three',3), ('four',4)] )

#access the dictionary

dict_number2

{'one': 1, 'two': 2, 'three': 3, 'four': 4}

 

 

General dict operations.

 

Here we have a dictionary dict_number1 with key-value pairs.

Lets carry out some operations on this.
  


dict_number1 {'one': 1, 'two': 2, 'three': 3, 'four': 4}

  

Indexing using key

 
Accessing elements of dict by using keys.
 
Key has to be used with quoates.
 

dict_number1['one']

#output

1

dict_number1['two']

#output

2

dict_number1['three']
#output

3

 

 

Here keys are sting objects,
 

keys should be provided in quotes, to access the values

 

If you try to access the value with key without quotes, you will get a NameError.

 
 


dict_number1[three]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>;

NameError: name 'three' is not defined

 
 

If three is referring to any valid key of dict,

then it can be used to access the value.

for example three = ‘two’ , this is a silly example but just understand

let’s continue with this.

 
 

three = 'two'

dict_number1[three]

output:

2

 

How to check an element present in dictionary ?

 
Using in operator we check element present or not.

 

in operator

in operator evaluates to True if key exists, otherwise False.

 
Ex 1:
 
check ‘one’ key exists in dict

 
 


dict_number = {'one' : 1, 'two': 2, 'three': 3, 'four':4}

if 'one' in dict_number:

    print("key exists")

else:

    print("key doesn't exists")


output:

key exists

 

&nbsp

Ex 2:

check ‘six’ key doesn’t exists in dict

 
 

if 'six' in dict_number:

    print("key exists")

else:

    print("key doesn't exists")


#output:

key doesn't exists

 

 

 

Built-in functions on dict

  

len()

 
Returns number of key-value pairs in dict.

 

dict_numbers = dict(one=1, two=2,three=3, four=4)

dict_numbers

{'one': 1, 'two': 2, 'three': 3, 'four': 4}

len(dict_numbers)

#output:

4

 

max()

Returns the maximum key.

 

We have two examples here,

In the first example key is string type

and in second example key is of type integer.

 

Ex 1:
 


max(dict_numbers)

output:

'two' 

Here the output is ‘two’ based on alphabets comparison

 

Ex 2:
 

max( {1:'first',2:'second',3:'third'} )

output:

3

 

Here value of key 3 is maximum.

 
 

min()

 

Returns the minimum key.
 
Similar to above example, but returns the minimum string and minimum integer key.
 
Ex 1:
 

min(dict_numbers)

output:

'four' 

As above result ‘four’ is based on alphabets comparison

 
#Ex 2:
 

min( {1:'first',2:'second',3:'third'} )


output:
1

 

 

sorted()

 
Returns a list of sorted keys.

This is also similar to above example.
 
Ex 1.
 

sorted(dict_numbers)

output:

['four', 'one', 'three', 'two'] # alphabetical sorting

 
Ex 2.

 

sorted({1:'first',2:'second',3:'third'})

output:

[1, 2, 3]

  

Built-in dictionary methods.

 

 

MethodDiscription
get()get value with key
pop()remove and return value
clear()clear dict
keys()get all the keys
values()get all the values
items()get all the items, keys and values
setdefault()add and set a default value to a key, if key not present
update() merge another dict
fromkeys()return dict with key and value given

  

get(key)

 
Returns a value if the key exists, returns None otherwise.

  

dict_number.get('two')

output:

2

dict_number.get('six')

output:

#nothing is printed on screen

 

 

pop(key)

Removes the key from the dict, returns the associated value.

 

dict_number = {'one' : 1, 'two': 2, 'three': 3, 'four':4}

dict_number.pop('two')

output:

2


#check the whether the item is removed

dict_number

output:

{'one': 1, 'three': 3, 'four': 4}

 

 

clear()

Removes all the items from dictionary.

dict_number.clear()
 
Check the dictionary, it should be an empty dict
 

dict_number

output:

{}

 

keys()

 
Returns all the keys in the dict, as sequence.

 

dict_number = {'one' : 1, 'two': 2, 'three': 3, 'four':4}

dict_number.keys()

output:

dict_keys(['one', 'two', 'three', 'four'])

 

 

values()

 
Returns all the values in the dict, as sequence.
 

dict_number.values()

output:

dict_values([1, 2, 3, 4])

 
 

items()

 
Returns all the items in the dict, as key-value pairs.

  

dict_number.items()

output:

dict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4)])

 
 

setdefault()

 
setdefault(key, default_value)

 

If key is present in dictionary, returns the associated value.

If key is not present, adds the key and sets the

given default_value as the value and returns this value.

If default is not given, it defaults to None

 

Ex 1:
 
check the key ‘five’ exists if not add,

it and assign a default value 5 to it
 

dict_number.setdefault('five', 5)

output:

5

 
Ex 2:
 

check the dict for new key and default value

 

dict_number

output:

{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

 

Ex 3:
 
Try to set a default value to an existing key
 

dict_number.setdefault('three', 5)

#output:

3

 
check the dict, if value of ‘three’ is changed ?

 

dict_number

#output:

{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

 

The value of the existing key ‘three’ is not changed.
  

update(new_dict)

 

Merge or update values from the new_dict original dict.

Updates the values if key exists.

 

Its similar to
 

for k in new.keys(): 
    d[k]= new[k]

 
 

Lets create two dictionary to verify this.
 

 

dict_number = dict(one=1, two=2, three=3, four=4)

dict_number

#output:

{'one': 1, 'two': 2, 'three': 3, 'four': 4}


dict_number2 = dict(one=10, two=20, six=6, seven=7)

dict_number2

#output:

{'one': 10, 'two': 20, 'six': 6, 'seven': 7}

dict_number.update(dict_number2)

dict_number

#output

{'one': 10, 'two': 20, 'three': 3, 'four': 4, 'six': 6, 'seven': 7}


 

fromkeys()

 
fromkeys(iterable, value=None, /)

Returns a new dict with keys from iterable and values equal to value.

 

Useful when you want create dictionary with initial value for all the keys.
 
Here we have a set named emp_key, which is passed as an argument to fromkeys()
 


emp_key = {'first_name', 'last_name', 'age','emp_id'} 


#Now create a dict emp with keys as elements of emp_key set.


# emp_key set, passed as a parameter.

emp = dict.fromkeys(emp_key,None)

#check the dictionary contents.

emp

#output:
{'last_name': None, 'age': None, 'emp_id': None, 'first_name': None}

 

 

Iterating through dict.

 
Like other sequences we can iterate through dictionary.

Through iteration we can extract, keys() or values () or both as items() form dictionary.
 

Accessing keys and values, with items() dict built-in method.

  


dict_number = {'one': 10, 'two': 20, 'three': 3, 'four': 4, 'six': 6, 'seven': 7}

for k,v in dict_number.items():

    print("{0} : {1}".format(k,v)


#output:


one : 10

two : 20

three : 3

four : 4

six : 6

seven : 7

 

 

Accessing only keys, with keys() dict built-in method.

  

for k in dict_number.keys():

    print(k)

#output:

one
two
three
four
six
seven

 

 

Accessing only values with value() dict built-in method.

 


for v in dict_number.values():

    print(v)
output:


10
20
3
4
6
7

  

Thats pretty much covers the basics of dictionary.

   Try out dictionary exercises.