Dictionary in Python

Dictionary is a set of ordered ( version 3.7 ), 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

Without any elements and using constructor.
my_dict=dict()
print(type(my_dict))
my_dict={}
print(type(my_dict))
With key value pairs ( data )
my_dict={1:'Alex',2:'Ronald'}
print(my_dict)
Output
{1: 'Alex', 2: 'Ronald'}

Python dictionary creating and modifying key value pairs using various methods and functions

Add , remove , update elements

Methods of dictionary object
Method Description
clear() Delete all elements of the dictionary
copy() Copy and create new dictionary
fromkeys() Creating dictionary using keys
get() Collect the value of the input key
items() View object with key value pair
keys() View object with keys
popitem() remove latest added item as a tuple of key value pair
pop() remove the value of input key
setdefault() Getting or adding key with value
update() Adding or updating key and value
values() View object listing the values
Number of keys present by len()
my_dict={'a':'Alex','b':'Ronald'}
print(len(my_dict))
Output
2
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
print(len(my_dict))
Output
3
Length of elements within the key
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
print(len(my_dict['a']))
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

Creating a list using the values

my_dict={'a':'One','b':'Two','c':'Three'}
x=list(my_dict.values()) # list of values 
print(x) # ['One', 'Two', 'Three']

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
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 

Getting Key by using Value of a dictionary

But this requirement is not for which dictionary is usually used. If possible then while creating the dictionary, key and value can be changed.

However here is the solution for getting key by using value.
my_dict={'a':'Alex','b':'Ronald'}
for i,j in my_dict.items():
    if j=='Ronald':
         print(i)
Output
b
When we use list as value of a dictionary, we can get other values by using any one element of the list. Here by using matching name we get the connected mark ( integer value inside list ) and the key.
my_dict={'a':['Alex',30],'b':['Ronald',40],'c':['Ronn',50]}
# display the mark of the matching name along with id 
for i,j in my_dict.items():
    if j[0]=='Ronald':
         print("Mark:",j[1], ", Key or id :",i)
Output
Mark: 40 , Key or id : b
Searching values for matching element
for i,j in my_dict.items():
    if 'Ronn' in j:
      print(i,">>",j)

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
Note: We can't keep duplicate keys in a dictionary, however duplicate values are allowed.

del with dictionary

The keyword del is used to remove any element or the complete dictionary object.

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
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'}
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
print(my_dict['a'][:1])# Output : ['Alex']
print(my_dict['a'][:2])# Output : ['Alex', 30]
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)

Dictionary from database record set

More about MySQL database and connection here
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_tutorial")
query = "SELECT *  FROM student LIMIT 0,5"
my_data = list(my_conn.execute(query))  # SQLAlchem engine result set
my_dict = {} # Create an empty dictionary
my_list = [] # Create an empty list
for row in my_data:
    my_dict[[row][0][0]] = row  # id as key
    my_list.append(row[1]) # name as list
print(my_dict)
print(my_list)
# Print the other values for matching Name
for i, j in my_dict.items():
    if j[1] == "Arnold":
        print(i, j[0], j[1], j[2])

Question

Find out the frequency of occurrence of chars in a string?
my_str='Welcome to Python'
my_dict={}
for i in my_str:
  if i in my_dict:
    my_dict[i] = my_dict[i] + 1
  else:
    my_dict[i]  = 1
print(my_dict)
Output
{'W': 1, 'e': 2, 'l': 1, 'c': 1, 'o': 3, 'm': 1, ' ': 2,
 't': 2, 'P': 1, 'y': 1, 'h': 1, 'n': 1}
Getting unique elements and counting the occurrence by using get().

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


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







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