Python Dictionary

Estimated reading: 2 minutes 1123 views

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['Age12'])

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

Dictionary Update Items

Using Below Code snippts shows the Updating Items in dicitionary.

					dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # we are adding the key and value pair

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'
del test_dict ;        # delete entire dictionary

Loop Dictionaries

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

					test_dict = {1:'aakash',2:'kumar',3:'Bihar',4:'piro'}
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}

Dictionary values()

Returns a list of all the values in the dictionary

					ex = {'Name': 'Zara', 'Age': 7}

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.

					ex = {'Name': 'Zara', 'Age': 7,'Class':'Second'}

Leave a Comment

Share this Doc