Home > Notes > python

Python Dictionary

python

Python Variable
Python Conditional statement
Python loops
Python List
Python Tuple
Python String
Python Set
Python Dictionary
Python Functions
Python Exceptions
Python File Operation
Python Map
Python Lambda
Python Filter
Python OOPS

Python Dictionary

Dictionary overview

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates. Dictionaries are written with curly brackets, and have keys and values:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict['Name'])
#print (dict['Age12'])
#print(dict)

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets: There is also a method called get() that will give you the same result:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict["Name"])
print(dict.get("Name"))

#print (dict['Age12'])
#print(dict)

Dictionary Update Items

Using Below Code snippts shows the Updating Items in dicitionary.

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict["Age"] = 8

Dictionary Remove item

The del keyword removes the item with the specified key name:

test_dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
#del test_dict['Name']; # remove entry with key 'Name'
#test_dict.clear();     # remove all entries in dict
#del test_dict ;        # delete entire dictionary
#print(test_dict)

Loop Dictionaries

Loop through both keys and values, by using the items() method:

test_dict = {1:'aakash',2:'kumar',3:'Bihar',4:'piro'}
#print(test_dict.items())
#print(test_dict.items())
for k, v in test_dict.items():
  print(k," ",v)

Dictionary keys()

Returns a list containing the dictionary’s keys

ex = {'Name': 'Zara', 'Age': 7}
print(list(ex.keys()))

Dictionary values()

Returns a list of all the values in the dictionary

ex = {'Name': 'Zara', 'Age': 7}
print(list(ex.values()))

Dictinoary __contains__()

The __contains__() is used to check whether a key exists , if exists it will give true else False

dict = {'Name': 'Zara', 'Age': 7}
#print (dict.__contains__('Name'))  # __contains__('key')
#print (dict.__contains__('Sex'))

Dictionary len()

len() is use to count the number of key and value pair.

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(len(dict))
#print (dict['Age12'])
#print(dict)