Python Dictionary
Python dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair.
Let us see an example,
Here,
-Key PARAS GUPTA with a value 467
-Key ELENA JOSE with a value 450
-Key JOEFFIN JOSEPH with a value 480
Dictionaries are Python’s built-in mapping type. A map is an unordered, associative collection as you saw in the above key : value pair
Creating a Python Dictionary
A dictionary can be created in three different ways :
Dictionary using literal notation.
To declare a dictionary, the syntax is:
directory-name = {key : value, key : value, ……, keyN : valueN}
Here,
- Dictionary is listed in curly brackets, inside these curly brackets ( { } ), keys and values are declared.
- Each key is separated from its value by a colon (:) while each element is separated by commas.
- The keys in a dictionary must be immutable objects like strings or numbers.
- Dictionary keys are case sensitive.
- The values in the dictionary can be of any type.
For example, let us create and print the Marks dictionary:
>>> Marks = {'mannat':456,'paras gupta' : 467, 'arushi aggarwal' : 480} >>> Marks {'mannat': 456, 'paras gupta': 467, 'arushi aggarwal': 480}
Similarly, let us create another dictionary called Student with following key : value pairs:
>>> Student = { "Name" : "Surbhi Gupta", "Rollno" : 11, "Address" : "F2/27 - MIG Flat, Sec-7, Rohini", "Phone" : "7286798500" } >>> print (Student) {'Name': 'Surbhi Gupta' , 'Rollno': 11 , 'Address': 'F2/27 - MIG Flat, Sec-7, Rohini' , 'Phone': '7286798500'}
Dictionary using dict() function.
The dict( ) function is used to create a new dictionary with no items. For example
>>> weekdays = dict() # Creates an empty dictionary >>> weekdays ## Prints an empty string with no value {} 2nd Example >>> weekdays = dict(sunday=0,monday=1,tuesday=2,thursady=3) >>> weekdays {'sunday': 0, 'monday': 1, 'tuesday': 2, 'thursady': 3}
Creating an empty dictionary using {}
An empty dictionary can be created using {}. After creating an empty dictionary, we can use square brackets ( [ ] ) with keys for accessing and initializing dictionary values.
For example,
>>> weekdays = {} >>> weekdays[0] = 'Sunday‘ >>> weekdays[1] = 'Monday' >>> weekdays[2] = 'Tuesday' >>> print (weekdays) {0: 'Sunday', 1: 'Monday', 2: 'Tuesday'} Similarly, add remaining weekdays into the dictionary. >>> print (weekdays) {0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday'}
Accessing values of dictionary
Using KeyName
Value of a dictionary element can be accessed using its key name. Suppose we have a dictionary
Studdict ={ "Name": "Rohit Sharma", "Address": "Rohini", "Fees": 2000 }
You can access the items of a dictionary by referring to its key name, inside square brackets:
Get the value of the “Address” key:
x = Studdict["Address"] print(x) Output : Rohini
Using get() Method
There is also a method called get() that will give you the same result: Get the value of the “Address” key:
x = Studdict.get("Address") print(x) Output : Rohini
Iterating through Dictionary
Iterating (or traversing) a dictionary means, process, or go through each key of a dictionary with respective values. When dictionary keys are processed within a loop, the loop variable or a separate counter is used as a key index into the dictionary which prints each key: value elements.
The most common way to traverse the key: value is with a for a loop.
For example, let us we have a dictionary with the following key – values:
Emp = { "Shika Antony" : "Programmer", "Aju John" : "Teacher", "Shreya Rao" : "Teacher", "Hisham Ahmed Rizvi" : "Programmer", "Shreya Mathur" : "Accountant", "Pooja Agarwal" : "Teacher", "Shivani Behl" : "Programmer"} To iterate the key : value pair: >>> for E in Emp: print (E,":",Emp[E]) Shika Antony : Programmer Aju John : Teacher Shreya Rao : Teacher Hisham Ahmed Rizvi : Programmer Shreya Mathur : Accountant Pooja Agarwal : Teacher Shivani
Loop through both keys and values, by using the items() function
Emp = { } Emp['Hima John'] = 'Teacher' Emp['Rohan'] = 'Accountant' for x, y in Emp.items(): print(x, ":",y) Output Hima John : Teacher
Modifying & Deleting Dictionary Data
A dictionary value can be modified through the dictionary key. For example, let us first add a new key: value into the previous Emp dictionary.
>>> Emp['Hima John'] = 'Teacher‘ # a key : value added >>> for E in Emp: print (E,":",Emp[E]) Shika Antony : Programmer Aju John : Teacher Shreya Rao : Teacher Hisham Ahmed Rizvi : Programmer Shreya Mathur : Accountant Pooja Agarwal : Teacher Shivani Behl : Programmer Hima John : Teacher
Deleting dictionary value using key
The del statement removes a key-value pair from a dictionary. The dictionary data can only be deleted using the dictionary key. The syntax is:
del dictionary[key]
Here, the key can be either integer or string. For example, to delete “Hima John” the command is:
>>> del Emp["Hima John"] >>> for E in Emp: print (E,":",Emp[E]) Shika Antony : Programmer Aju John : Teacher Shreya Rao : Teacher Hisham Ahmed Rizvi : Programmer Shreya Mathur : Accountant Pooja Agarwal : Teacher Shivani Behl : Programmer
Dictionary Functions
A dictionary object has a number of functions and methods. The dot operator (.) is used along with the string to access string functions except for len() and sorted() function.
Sample dictionary for the below functions and method
Name = {'Anmol' : 14, 'Kiran' : 15, 'Vimal': 15, 'Amit' : 13, 'Sidharth' : 14, 'Riya' : 14, 'Sneha' : 13}
function | Description |
len() | This function gives the number of pairs in the dictionary.
print (“Length : %d” % len (Name)) # prints: Length : 7 |
copy()
|
This method copies the entire dictionary to a new dictionary.
NewName = Name.copy() print(NewName) Which prints: {‘Anmol’: 14, ‘Kiran’: 15, ‘Vimal’: 15, ‘Amit’: 13, ‘Sidharth’: 14, ‘Riya’: 14, ‘Sneha’: 13} |
get()
|
This method returns a value for the given key. If the key is not available then it returns the default value None.
print (“Age of Vimal is :”, Name.get(“Vimal”)) Which prints: Age of Vimal is: 15 |
item()
|
This method returns key and value, in the form of a list of tuples — one for each key : value pair.
print (“Names are: “, Name.items()) Names are: dict_items([(‘Anmol’, 14), (‘Kiran’, 15), (‘Vimal’, 15), (‘Amit’, 13), (‘Sidharth’, 14), (‘Riya’, 14), (‘Sneha’, 13)]) |
keys()
|
This method returns a list of all the available keys in the dictionary.
print (“Name keys are:”, Name.keys()) Which prints: Name keys are: dict_keys([‘Anmol’, ‘Kiran’, ‘Vimal’, ‘Amit’, ‘Sidharth’, ‘Riya’, ‘Sneha’]) |
values()
|
This method returns a list of all the values available in a given dictionary.
print (“Name values are:”, Name.values()) Which prints: Name values are: dict_values([14, 15, 15, 13, 14, 14, 13]) |
sorted()
|
This method returns a sorted sequence of the keys in the dictionary.
print(sorted(Name)) Which prints: [‘Amit’, ‘Anmol’, ‘Kiran’, ‘Riya’, ‘Sidharth’, ‘Sneha’, ‘Vimal’] |
update()
|
This method add/merge the content of a dictionary into another dictionary’s key-values pairs. This function does not return anything. While updating the contents, no duplicated key:value pair will be updated.
temp = {“Mathew” : 13, ‘John’ : None} # A new dictionary Name.update(temp) # Temp dictionary undated/added with Name print (Name) Which prints: {‘Anmol’: 14, ‘Kiran’: 15, ‘Vimal’: 15, ‘Amit’: 13, ‘Sidharth’: 14, ‘Riya’: 14, ‘Sneha’: 13, ‘Mathew’: 13, ‘John’: None} |
pop()
|
This method removes the item with key and return its value from a dictionary.
print (Name) Which prints: {‘Anmol’: 14, ‘Kiran’: 15, ‘Vimal’: 15, ‘Amit’: 13, ‘Sidharth’: 14, ‘Riya’: 14, ‘Sneha’: 13, ‘Mathew’: 13, ‘John’: None} Name.pop(“Mathew”) # returns: 13 print (Name) Which prints: {‘Anmol’: 14, ‘Kiran’: 15, ‘Vimal’: 15, ‘Amit’: 13, ‘Sidharth’: 14, ‘Riya’: 14, ‘Sneha’: 13, ‘John’: None} Name.popitem() # returns: (‘Mathew’, 13) print (Name) Which prints: {‘Anmol’: 14, ‘Kiran’: 15, ‘Vimal’: 15, ‘Amit’: 13, ‘Sidharth’: 14, ‘Riya’: 14, ‘Sneha’: 13} |
popitem()
|
This method removes key: value pair orderly and it always pops pairs in the same order.
Name.popitem() # returns: (‘John’, None) Name.popitem() # returns: (‘Sneha’, 13) print (Name) Which prints: {‘Anmol’: 14, ‘Kiran’: 15, ‘Vimal’: 15, ‘Amit’: 13, ‘Sidharth’: 14, ‘Riya’: 14} |