Problem Solving and Python Programming: UNIT IV: Lists, Tuples, Dictionaries

Dictionaries

Python Programming

Definition : In Python, dictionary is unordered collection of items. These items are in the form of key-value pairs.

Dictionaries      AU : Jan. 18, Dec.-19, Marks 12

Definition : In Python, dictionary is unordered collection of items. These items are in the form of key-value pairs.

• The dictionary contains the collection of indices called keys and collection of values.

• Each key is associated with a single value.

• The association of keys with values is called key-value pair or item.

• Dictionary always represent the mappings of keys with values. Thus each key maps to a value.


Fig. 4.3.1 Dictionaries

How to Create Dictionary ?

• Items of the dictionary are written within the {} brackets and are separated by commas

• The key value pair is represented using : operator. That is key:value

•  The keys are unique and are of immutable types - such as string, number, tuple.


• We can also create a dictionary using the word dict( ). For example –

>>> my_dictionary = dict({0:'Red', 1:'Green',2:'Blue'))

How to access the elements in dictionary ?

We can access the element in the dictionary using the keys. Following script illustrates it

test.py


 

1.  Operations and Methods

Basic operations

Various operations that can be performed on dictionary are :

1. Adding item to dictionary

We can add the item to the dictionary.For example

>>> my_dictionary = dict({0:'Red', 1:'Green',2:'Blue'})

>>> print(my_dictionary)

{0: 'Red', 1: 'Green', 2: 'Blue'}

>>> my_dictionary[3] = 'Yellow' #adding the element to the dictioary

>>> print(my_dictionary)

{0: 'Red', 1: 'Green', 2: 'Blue', 3: 'Yellow'}

>>> 

2. Remove item from dictionary

For removing an item from the dictionary we use the keyword del. For example

>>> del my_dictionary[2] #deleting the item from dictionary

>>> print(my_dictionary) #display of dictionary

{0: 'Red', 1: 'Green', 3: 'Yellow'}

>>> 

3. Updating the value of the dictionary

We can update the value of the dictionary by directly assigning the value to corresponding key position. For example -

>>> my_dictionary = dict({0:'Red', 1:'Green',2:'Blue')) #creation of dictionary

 >>> print(my_dictionary) #display of dictionary

{0: 'Red', 1: 'Green', 2: 'Blue'}

>>> my_dictionary[1]='Yellow' #updating the value at particular index

>>>print(my_dictionary) #display of dictionary

{0: 'Red', 1: 'Yellow', 2: 'Blue'} #updation of value can be verified.

>>> 

4. Checking length

The len() function gives the number of pairs in the dictionary. For example

>>> my_dictionary=dict({0:'Red', 1:'Green',2:'Blue'}) #creation of dictionary

>>> len(my_dictionary) # finding the length of dictionary

3 #meaning - that there are 3 items in dictionary

>>>

Methods in dictionary

Following are some commonly used methods in dictionary.


1. The clear method

This method removed all the items from the dictionary. This method does not take any parameter and does not return anything. For example

>>> my_dictionary={1:'AAA',2:'BBB',3: CCC'} # creation of dictionary

>>> print(my_dictionary) #display

{1: 'AAA', 2: 'BBB', 3: 'CCC"}

>>> my_dictionary.clear() #using clear method

>>> print(my_dictionary) #display

{ }

>>>

2. The copy method

The copy method returns the copy of the dictionary. It does not take any parameter and returns a shallow copy of dictionary. For example

>>> my_dictionary={1:'AAA',2:'BBB',3:"CCC"}

>>> print(my_dictionary)

{1: 'AAA', 2: 'BBB', 3: CCC'}

>>> new_dictionary=my_dictionary.copy()

>>> print(new_dictionary)

{1: 'AAA', 2: 'BBB', 3: 'CCC'}

>>> 

3. The fromkey method

The fromkeys() method creates a new dictionary from the given sequence of elements with a value provided by the user.

Syntax

dictionary.fromkeys(sequences, value])

The fromkeys() method returns a new dictionary with the given sequence of elements as the keys of the dictionary. If the value argument is set, each element of the newly created dictionary is set to the provided value.

For example

>>> keys = {10,20,30}

>>> values = 'Number'

>>> new_dict = dict.fromkeys(keys,values)

>>> print(new_dict)

{10: 'Number', 20: 'Number', 30: 'Number'}

>>>

4. The get method

The get() method returns the value for the specified key if key is in dictionary. This method takes two parameters key and value. The get method can return either key, or value or nothing.

Syntax

dictionary.get(keys, value])

For example

>>> student={'name':'AAA','roll': 10,'marks':98} #creation of dictionary

>>> print("Name: ",student.get('name'))

Name: AAA

>>> print("roll: ",student.get('roll'))

roll: 10

>>> print("marks: ",student.get('marks'))

marks: 98

 >>> print("Address: ", student.get('address')) #this key is 'address' is not specified in the list

Address: None #Hence it returns none

>>> 

5. The value method

This method returns the value object that returns view object that displays the list of values present in the dictionary.

For example :

>>> my_dictionary ={'marks 1:99,'marks2:96,'marks3:97}#creating dictionary

>>> print(my_dictionary.values()) #displaying values

dict_values([99, 96, 97])

>>> 

6. The pop method

This method The pop() method removes and returns an element from a dictionary having the given key.

Syntax

pop(keys, default])

where key is the key which is searched for removing the value. And default is the value which is to be returned when the key is not in the dictionary. For example

my_dictionary={1:'Red', 2:'Blue', 3:'Green'}#creation of dictionary

>>> val = my_dictionary.pop(1) #removing the element with key 1

>>> print("The popped element is: ",val)

The popped element is: Red

>>> val=my_dictionary.pop(5,3)

 #specifying default value. When the specified key is not present in the list, then the

#default value is returned.

>>>print("The popped element using default value is: ",val)

The popped element using default value is: 3 #default value is returned

>>>

 

Example 4.3.1 Define dictionary in Python. Do the following operations on dictionaries

i) Initialize two dictionaries with key and value pair.

ii) Compare the two dictionaries with master key list and print missing keys

iii) Find keys that are in first and not in second dictionary

iv) Find same keys in two dictionaries

v) Merge two dictionaries and create a new dictionary using a single expression.

AU : Dec.-19, Marks 10

Solution : Dictionary - Refer section 4.3.

i)

d1 = {1:"AAA",2:"BBB",3:"CCC"}

print("Dictionary#1")

print(d1)

print("Dictionary#2")

d2 = {10:"Pune",20:"Mumbai",30:"Chennai"}

print(d2)

ii)

First_Dict = {"Color": ["Red", "Blue", "Green", "Yellow"),

"Fruit": {"Mango", "Banana", "Apple"),

"Flower": ["Rose", "Jasmine", "Lotus", "Lily"),

"Country": ["India", "Japan"]}

Second_Dict = {"Color": ["Red", "Blue", "Green", "Yellow"],

"Fruit": ["Mango", "Banana", "Apple"],

"Flower": ["Rose", "Tulip", "Daffodil",),

"City":["Pune", "Chennai"]}

key_lst=[ ]

values_lst=[ ]

for key, value in First_Dict.items() and Second_Dict.items():

if key in First_Dict.keys() and Second_Dict.keys():

if key in Second_Dict.keys() and First_Dict.keys() :

continue

else:

key_lst.append(key)

else:

key_lst.append(key)

if value in First_Dict.values() and Second_Dict.values():

if value in Second_Dict.values() and First_Dict.values() :

continue

else:

values_lst.append(value)

else:

values_lst.append(value)

for key, value in Second_Dict.items() and First_Dict.items():

if key in First_Dict.keys() and Second_Dict.keys():

if key in Second_Dict.keys() and First_Dict.keys() :

continue

else:

key_lst.append(key)

else:

key_lst.append(key)

if value in First_Dict.values() and Second_Dict.values():

if value in Second_Dict.values() and First_Dict.values():

continue

else:

values_lst.append(value)

else:

values_lst.append(value)

print("Missing Keys: ",key_lst[0],": Missing Values", values_lst[0])

print("Missing Keys: ",key_lst[1],": Missing Values", values_lst[1])

Output

Missing Keys: City : Missing Values (Pune', 'Chennai']

Missing Keys: Country : Missing Values ['India', 'Japan']

>>> 

iii)

d1 = {"Color":"Red", "Fruit":"Mango", "Flower":"Rose", "Country":"India"}

d2 = {"Color": "Red", "Fruit": "Mango","City":"Pune"}

print(d1.keys()-d2.keys())

iv)

d1 = {"Color": "Red", "Fruit":"Mango", "Flower":"Rose", "Country":"India"}

d2 = {"Color": "Red", "Fruit":"Mango", "City":"Pune"}

d3 = [ ]

for item in d1.keys():

if item in d2.keys():

d3.append(item)

print(d3)

Output

['Color', 'Fruit']

>>> 

v)

dict1 = {1: "AAA", 2:"BBB"}

dict2 = {3: "CCC", 4:"DDD"}

result = (key:value for d in (dict1, dict2] for key,value in d.items()}

print(result)

Output

{1: 'AAA', 2: 'BBB', 3: 'CCC", 4: 'DDD'}

>>> 

Review Questions

1. What is a dictionary in Python ? Give example.

AU: Jan.-18, Marks 4

2. Appraise the operations for dynamically manipulating dictionaries.

AU: Jan.-18, Marks 12

 

Problem Solving and Python Programming: UNIT IV: Lists, Tuples, Dictionaries : Tag: Engineering Python : Python Programming - Dictionaries