Codied To Clipboard !
Home > Notes > python
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)
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)
Using Below Code snippts shows the Updating Items in dicitionary.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict["Age"] = 8
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 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)
Returns a list containing the dictionary’s keys
ex = {'Name': 'Zara', 'Age': 7} print(list(ex.keys()))
Returns a list of all the values in the dictionary
ex = {'Name': 'Zara', 'Age': 7} print(list(ex.values()))
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'))
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)