You can learn about Dictionaries in Python Programs with Outputs helped you to understand the language better.

Python Programming – Creation, Initialization and Accessing The Elements In A Dictionary

A collection that allows us to look up information associated with arbitrary keys is called a mapping. Python dictionaries are mappings. Some other programming languages provide similar structures called hashes or associative arrays. The dictionary

can be created in Python by listing key: value pairs inside curly braces. A simple dictionary shown in Figure 9.1 stores some usernames and passwords.
# Creating a Dictionary
>>> password = {“Aman”:”101″, “Preeti”:”204″, “Babita”:”107″}
Notice that keys and values are joined together with a and commas are used to separate the pairs. The main use of the dictionary is to look up the value associated with a particular key. This is done through indexing notation. More than one entry per key is not allowed, which means no duplicate key is allowed.

  • Dictionaries are collections of data that associate a unique key with each value.

An empty dictionary (without any items) is written with just two curly braces, like this: { }.
>>> dict1 = { } # it is an empty dictionary with no elements
>>> dict1
{ }
type( ) returns the type of the passed variable. If passed variable is dictionary, then it would return the object representing the ‘diet’ class.
>>> type (dic1)
<class ‘dict’>
To create an empty dictionary, you can either use the dict( ) function with no inputs, or assign a pair of curly brackets with nothing in between to a variable. You can confirm that both methods will produce the same result. For example,

empty = { }
my_empty = dict( )
empty == my_empty

To create dictionary using built-in function dict( ), the argument to dict( ) should be a sequence of key- value pairs.

# using built-in function dict( )
my_dict = diet({1:’apple’, 2:’banana’})
The following examples store employee information as a dictionary:
>>> dict2 = {‘name’: ‘Raj’, ‘deptcode’:
7} # Creating a Dictionary
>>> dict1, dict2
({ }, {‘deptcode’: 7, ‘name’: ‘Raj’})
To access dictionary elements, you use the familiar square brackets along with the key to obtaining its value:
>>> dict2[‘name’] # accessing a element
using key
‘Raj ‘
Dictionary dict1 is empty while dict2 has two data items. The keys in dict2 are ‘name’ and ‘deptcode’, and their associated value items are ‘Raj’ and 7, respectively. Access to the value is through the key, as you can see from the explicit access to the ‘name’ key.
If you attempt to access a data item with a key that is not a part of the dictionary, you get an error:
>>> dict2[‘salary’]
Traceback (most recent call last):
File “<pyshe11#1>”, line 1, in <module> dict2[‘salary’]
KeyError: ‘salary’

  • You can also access a value for a key using the get( ) method. The difference while using get( ) is that it returns None instead of KeyError if the key is not found.

In this example, you tried to access a value with the key ‘salary’ which, as you know, does not exist in the code given above. The best way to check if the dictionary has the specific key or not is by using the following syntax: ‘key name in the dictionary
It will return True if the dictionary has that key and False otherwise.

‘key name in the dictionary
It will return True if the dictionary has that key and False otherwise.
>>> ‘salary’ in dict2
>>> ‘name’ in dict2
>>> dict2[‘name’]
‘ Raj ‘
Once the in has returned True, meaning that the key exists, then you can access it without having to worry about getting the KeyError.

  • In Python 2, the has_key( ) method checks whether a dictionary has a given key or not. The expression d. has_key(k) is equivalent to k in d. The has_key ( ) method has been removed from Python 3.
    Instead of:
    dictionary. has_key(‘key name’)
    you should use:
    ‘key name in the dictionary

Let us take a look at another dictionary example, using keys other than strings:
>>> dict3 = { }
>>> dict3 [ 1 ] = ‘abc’
>>> dict3 [ ‘ 1 ‘ ] = 3.14159
>>> dict3 [ 3 . 2 ] = ‘xyz’
>>> dict3
{ 3 . 2 : ‘xyz’, 1: ‘abc’, ‘1’: 3.14159 }
Rather than adding each key:value pair individu¬ally, you could also enter all the data for dict3 at the same time. For example,
dict3 = { 3.2: ‘xyz’, 1: ‘abc’, ‘1’: 3.14159 }

Traversing a Dictionary

Traversing a dictionary means visiting each element of the dictionary to display its values on the screen. Similar to the lists, you can use a “for in” loop to traverse through a dictionary. In general, it is the keys that enable iteration.

Demo of traversing a dictionary.

# Traversing a Dictionary
mydict = { 1 : ‘ Apple ‘ 2 : ‘ Banana ‘ , 3 : ‘ Orange ‘ , 4 : ‘ Grapes ‘ }
for i in mydict :
print ( i , ” : ” , mydict [ i ] )RUN
1 : Apple
2 : Banana
3 : Orange
4 : Grapes

In Figure 9.2 ‘in’ operator is used with for loop to iterates each key of a dictionary.

Appending Values in a Dictionary

Python allowed the dictionary object to be mutable. Hence, the add or update operations are permissi¬ble. In Python dictionary, addition of elements can be done in multiple ways. One value at a time can be added to a dictionary by defining value along with the key e.g. DictfKey] = “Value”. For example,
>>> dict2[‘name’] = ‘Raju’ # update
existing entry
>>> dict2[‘deptcode’] = 5 # update existing entry
>>> dict2[‘deptname’] = ‘Sales’ # add new entry

If the key does exist, then its previous value will be overridden by its new value. You may also add the contents of an entire dictionary to another dictio-nary by using the update() built-in method. Whenever you add an element whose key already exists, it’s value will get changed to the new value. On adding a fresh “key: value” pair, a new element will get added to the dictionary. For example,
>>> d1 = {‘a’: 10, ‘b’: 200, ‘c’: 30}
>>> d1.update([(‘b’, 20), (‘d’, 40)])
>>> d1
{‘a’: 10, ‘b’: 20, ‘C’: 30, ‘d’: 4 0}
In the example, key ’b’ already exists in d1, so its value is updated from 200 to 20, and however, there is no key’d’ in dl, so that key-value pair is added.


Demo 0f append and update the dictionary.

# Demo of append and update the dictionary
# Original dictionary created with name, class and year
mydict={“name”: “Aman”, “class”:”XII”, “year”:2019}
print(mydict)# Dictionary appended with “stream = Science”
mydict[“stream”] = “Science”
print(mydict)# Dictionary updated with “stream = Commerce” instead of Science
{‘ name’ ‘Aman’ , ‘class’ ‘XII’, ‘year’: 2 019}
{‘name’ ‘Aman’ , ‘class’ ‘XII’, ‘year’: 2019, ‘stream’: ‘Science’}
{‘ name’ ‘Aman’, ‘class’ ‘XII’, ‘year’: 2019, ‘stream’: ‘Commerce’}

Removing Dictionary Elements and Dictionaries

You can remove item from the existing dictionary by using del statement. You can either remove individ¬ual dictionary elements or clear the entire contents of the dictionary. If you really want to “remove” the entire dictionary, use the del statement. Here are some deletion examples for dictionaries and dictio¬nary elements:
de1 dict2[‘name’] # remove entry with key ‘name’
dict2.clear ( ) # remove all entries in
del dict2 # delete entire dictionary, i.e., dict2
Note- del dict2 will delete the entire dictionary and hence printing it after deletion will raise an Error.

  • The del keyword removes the item with the specified key name or can also delete the dictionary com¬pletely.

Let’s Try

Write the output of the following:

>>> month = {‘Jan’: 1, ‘Feb’: 2, ‘Mar’: 3, ‘Apr’: 4, ‘May’: 5, ‘June’: 6}
>>> month[‘Feb’]
>>> di = {‘a’: 10, ‘b’: 20, ‘c’: 30}
>>> print(di.get(‘b’) )
>>> print(di.get(‘x’))
d1 = {‘Rohan’: 18,’Raj’:24,’Dev’:- 22,’Robert’:27}
de1 d1 [‘Dev’]
numbers = range ( 10 )
dict 1 = { }
# Add values to ‘dict1’ using for loop for i in numbers:
if i%2==0 :
dict1 [ i ] = i**2
dict1 [ i ] = i**3
dict1 = { ‘ a ‘ : 5 , ‘ b ‘ : 10 , ‘ c ‘ : 15 , ‘ d ‘ : 20 , ‘ e ‘ : 25 }
#check for items greater than 2
dict2 = {x:y for (x,y) in dict1.items ( ) if y>10}
print (dict2)

Leave a Reply

Your email address will not be published. Required fields are marked *