A dictionary contains a collection of indices, which are called keys, and a collection of values.
Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item.
A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.
In mathematical language, a dictionary represents a mapping from keys to values, so you can also say that each key ―maps to a value.
The function dict creates a new dictionary with no items. Because dict is the name of a built-in function.
The collections of the key-value pairs are enclosed within the curly braces {}
The built-in python dictionary methods along with the description are given below.
SN | Method | Description |
---|---|---|
1 | dic.clear() | The clear() method removes all elements from the set |
2 | dict.copy() | It returns a shallow copy of the dictionary. |
3 | dict.fromkeys(iterable, value = None, /) | Create a new dictionary from the iterable with the values equal to value. |
4 | dict.get(key, default = "None") | It is used to get the value specified for the passed key. |
5 | dict.has_key(key) | It returns true if the dictionary contains the specified key. |
6 | dict.items() | It returns all the key-value pairs as a tuple. |
7 | dict.keys() | It returns all the keys of the dictionary. |
8 | dict.setdefault(key,default= "None") | It is used to set the key to the default value if the key is not specified in the dictionary |
9 | dict.update(dict2) | It updates the dictionary by adding the key-value pair of dict2 to this dictionary. |
10 | dict.values() | It returns all the values of the dictionary. |
11 | len() | The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string. |
12 | popItem() | The popitem() method removes the item that was last inserted into the dictionary. |
13 | pop() | The pop() method takes a single argument (index) and removes the item present at that index. |
14 | count() | count() method searches the substring in the given string and returns how many times the substring is present in it. |
15 | index() | The index() method searches an element in the list and returns its index |
We have discussed previously how the data can be accessed in the list and tuple by using the indexing.
The dictionary value can be accessed by using the keys as the keys are unique in the dictionary.
--- Student details --- Name : Prayag Roll No : 15 Tutor : AIMTOCODE Course : Python Fees : 29
In above, example, we are aceessing and printing the each values separately by using their unique key from the dictionary.
in Python, it also provides us an alternative way of accessing the value by using the get() method to access the dictionary values.
However, it will give the same result as shown below:
Student details allready entered .... {'Name': 'Prayag', 'fee': 0, 'rno': 15, 'tutor': 'AIMTOCODE', 'course': 'Python'} Enter the details of Student.... Name: Prayag Rno: 15 tutor: AIMTOCODE course:Python fee:0 ---Entered new student's details--- {'Name': 'Prayag', 'fee': '0', 'rno': 15, 'tutor': 'AIMTOCODE', 'course': 'Python'}
Dict = {"Name": "Prayag","Age": 21}
In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.
Student Details .... {'Name': 'Prayag', 'Age': 21, 'roll no: ': 15, 'Tutorial': 'AIMTOCODE'}
This output format is also an input format. For example, you can create a new dictionary with four items:
We can also delete the item of the dictionary using del keyword as shown below
---Student detail--- {'Name': 'Prayag', 'fee': 0, 'rno': 15, 'tutor': 'AIMTOCODE', 'course': 'Python'} Deleting Student Name and Tutor: Modified Student Detail is: {'fee': 0, 'rno': 15, 'course': 'Python'} Deleting dictionary: Student Now trying to print againerror we get:
Traceback (most recent call last): File "delete-dictionary.py", line 13, in <module> print(Student) NameError: name 'Student' is not defined
If you use a dictionary in a for statement, it traverses the keys of the dictionary.
For example, prints each key of the dictionrary:
Student = {"Name": "Prayag", "Rno": 15, "Tutor":"AIMTOCODE", "Subject": "Python", "Fee":2000} for a in Student: print(a);
Name Rno Tutor Subject Fee
Student = {"Name": "Prayag", "Rno": 15, "Tutor":"AIMTOCODE", "Subject": "Python", "Fee":2000} for a in Student: print(Student[a]);
Prayag 15 AIMTOCODE Python 2000
Student = {"Name": "Prayag", "Rno": 15, "Tutor":"AIMTOCODE", "Subject": "Python", "Fee":2000} for a in Student.items(): print(a);
('Name', 'Prayag') ('Rno', 15) ('Tutor', 'AIMTOCODE') ('Subject', 'Python') ('Fee', 2000)
Suppose you are given a string and you want to count how many times each letter appears.
There are several ways you could do it:
def histogram(s): d = dict() for c in s: if c not in d: [c] = 1 else: d[c] += 1 return d
The name of the function is histogram, which is a statistical term for a collection of counters (or frequencies). The first line of the function creates an empty dictionary. The for loop traverses the string. Each time through the loop, if the character c is not in the dictionary, we create a new item with key c and the initial value 1 (since we have seen this letter once). If c is already in the dictionary we increment d[c].
>>> h=histogram('python programmimg') 17 >>> h {'a': 1, ' ': 1, 'g': 2, 'i': 1, 'h': 1, 'm': 3, 'o': 2, 'n': 1, 'p': 2, 'r': 2, 't': 1, 'y': 1}
The histogram indicates that the letters 'a ' and ' ' appear once; 'g' appears twice, and so on. Dictionaries have a method called get that takes a key and a default value. If the key appears in the dictionary, get returns the corresponding value; otherwise it returns the default value.
The built-in python dictionary methods along with the description are given below.
SN | Function | Description |
---|---|---|
1 | cmp(dict1, dict2) | It compares the items of both the dictionary and returns true if the first dictionary values are greater than the second dictionary, otherwise it returns false. |
2 | len(dict) | It is used to calculate the length of the dictionary. |
3 | str(dict) | It converts the dictionary into the printable string representation. |
4 | type(variable) | It is used to print the type of the passed variable. |