Dictionary in Python

Dictionary is a set of unordered, changeable and indexed key value pairs.

Each key and value are separated by colon : and each pair of key value is separated by comma ,

Declaring a dictionary

my_dict={1:'Alex',2:'Ronald'}
print(my_dict)
Output
{1: 'Alex', 2: 'Ronald'}
Creating dictionary by using fromkeys()
x=('a','b','c')
y=('value1')
my_dict=dict.fromkeys(x,y)
print(my_dict)
Output is here
{'a': 'value1', 'b': 'value1', 'c': 'value1'}
Getting the value by setdefault()
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
x=my_dict.setdefault('b')
print(x)
Output is
Ronald
If the key is not found, then it will insert the data
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
x=my_dict.setdefault('d','Ravi')
print(my_dict)
Output is here
{'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn', 'd': 'Ravi'}
Number of elements present by len()
my_dict={'a':'Alex','b':'Ronald'}
print(len(my_dict))
Output
2
Displaying elements based on position is not possible as dictionary is unindexed. This will give error message.
my_dict={'a':'Alex','b':'Ronald'}
print(my_dict[0])
Above lines will generate error

Displaying value through key

my_dict={'a':'Alex','b':'Ronald'}
print(my_dict['b'])
Output
Ronald
Using get()
my_dict={'a':'Alex','b':'Ronald'}
print(my_dict.get('a'))
Output
Alex
get() takes one optional parameter to return of the key is not found.
my_dict={'a':'Alex','b':'Ronald'}
print(my_dict.get('c','Not found')) # Not found

Displaying all items by looping

We used for loop to display all keys of the dictionary.
my_dict={'a':'Alex','b':'Ronald'}
for i in my_dict:
 print(i)
Output is here
a
b
To display values by using for loop
my_dict={'a':'Alex','b':'Ronald'}
for i in my_dict:
 print(my_dict[i])
Output is here
Alex
Ronald
Using items() we can list both keys and values
my_dict={'a':'Alex','b':'Ronald'}
for i,j in my_dict.items():
 print(i,j)
Output
a Alex
b Ronald
Display only values by values()
my_dict={'a':'Alex','b':'Ronald'}
for i in my_dict.values():
 print(i)
Output
Alex
Ronald
Searching key by if condition check
my_dict={'a':'Alex','b':'Ronald'}
if 'b' in my_dict:
 print("Yes, it is there ")
else:
 print("No, not there")  
Output
Yes, it is there
Searching value by using values()
my_dict={'a':'Alex','b':'Ronald'}
if 'Ronald' in my_dict.values():
 print("Yes, it is there ")
else:
 print("No, not there")
Output is here
Yes, it is there 

Add , remove , update elements

Add item
my_dict={'a':'Alex','b':'Ronald'}
my_dict['c']='Ronn'
print(my_dict)
Output is here
{'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn'}
Add item by using update() method
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict.update({'d':'John'})
print(my_dict)
Output is here
{'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn', 'd': 'John'}
We can update any value by using update()
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict.update('b','Ravi')
print(my_dict)
{'a': 'Alex', 'b': 'Ravi', 'c': 'Ronn'}
Note: We can't keep duplicate keys in a dictionary, however duplicate values are allowed.
Remove item by using pop() by giving key as input. Before removing we added one element having key c.
my_dict={'a':'Alex','b':'Ronald'}
my_dict['c']='Ronn'
my_dict.pop('b')
print(my_dict)
Output
{'a': 'Alex', 'c': 'Ronn'}
Removing last item by using popitem()
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict.popitem()
print(my_dict)
Output
{'a': 'Alex', 'b': 'Ronald'}
Removing a particular key value pair by using del() and the key
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
del my_dict['b']
print(my_dict)
Output
{'a': 'Alex', 'c': 'Ronn'}
If we don’t mention the key in above code then dictionary will be deleted. This code will generate error message.
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
del my_dict
print(my_dict)
Error message is here
name 'my_dict' is not defined
We can remove all elements of the dictionary by using clear() method.
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict.clear()
print(my_dict)
Output is here ( all elements are removed)
{}
Copying a dictionary by using copy() method.
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict1=my_dict.copy()
print(my_dict1)
Output is here
{'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn'}
Copying a dictionary by using dict() method
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict1=dict(my_dict)
print(my_dict1)
Output
{'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn'}
Collecting keys from the dictionary by using keys()
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_keys=my_dict.keys()
print(my_keys)
Output is here
dict_keys(['a', 'b', 'c'])
We can display all elements
my_dict={'a':'Alex','b':'Ronald','c':'Ronn'}
my_keys=my_dict.keys()
for i in my_keys:
    print(i)
Output is here
a
b
c
Get maximum or minimum element based on Keys or Values of a dictionary.

Merging of two Dictionary

Using update
my_dict1={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict2={'d':'Rabi','b':'Kami','c':'Loren'}
my_dict1.update(my_dict2)
print(my_dict1)# {'a': 'Alex', 'b': 'Kami', 'c': 'Loren', 'd': 'Rabi'}
my_dict1={'a':'Alex','b':'Ronald','c':'Ronn'}
my_dict2={'d':'Rabi','b':'Kami','c':'Loren'}
my_out={**my_dict1,**my_dict2}
print(my_out) # {'a': 'Alex', 'b': 'Kami', 'c': 'Loren', 'd': 'Rabi'}

Dictionary containing List

We can store multiple elements by using List and store them in a dictionary. Check this code , the outputs are also written within comments.
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
print(my_dict['a'][0]) # Output : Alex
print(my_dict['c'][1]) # Output : 50
We can add more elements like one more list to this dictionary
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
print(my_dict['a'][0]) # Output : Alex
print(my_dict['c'][1]) # Output : 50

my_dict.update({'d':['Ravi',60]})
print(my_dict)
Getting unique elements and counting the occurrence by using Counter.

  1. Exercise on Dictionary
  2. Ask for Name and mark of three students
    Create a dictionary with this and print them
  3. Following details of the student are to be stored.

    Name ( this will be key of the dictionary )
    Mark in three subjects i.e Physics , Chemistry , Math
    Attendance in number of days

    Create a dictionary and store three student details as mentions above.

    Print the dictionary
  4. Display all students name and attendance
  5. Create one csv( comma separated value ) file with id ( integer) , name(string), mark1(integer ), mark2(integer),mark3(integer), attendance(integer)
    Read the file and using the data create one dictionary. The first column id of the csv file should be the key and rest of the data should be value of the dictionary.
    One sample csv file is kept here with some data. Same can be used.
    1,Ravi,20,30,40,120
    2,Raju,30,40,50,130
    3,Alex,40,50,60,140
    4,Ronn,50,60,70,150
Solution

Python



plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer