Dictionary in Python
Dictionary in Python
The data type dictionary fall under mapping. It is a mapping between a set of keys and a set of values. The key-
value pair is called an item. A key is separated from its value by a colon : and consecutive items are separated by
commas. Items in dictionaries are unordered, so we may not get back the data in the same order in which we had
entered the data initially in the dictionary.
Creating a Dictionary:
To create a dictionary, the items entered are separated by commas (,) and enclosed in curly braces {}.
Each item is a key value pair, separated through colon (:). The keys in the dictionary must be unique and should
be of any immutable data type, i.e., number, string or tuple. The values can be repeated and can be of any data
type.
We have already seen that the items of a sequence (string, list and tuple) are accessed using a technique called
indexing.
The items of a dictionary are accessed via the keys rather than their relative positions or indices.
The following example shows how a dictionary returns the value corresponding to the given key:
Dictionaries are mutable which implies that the contents of the dictionary can be changed after it has been created.
We can add a new item to the dictionary as shown in the following example:
The existing dictionary can be modified by just overwriting the key-value pair.
The membership operator in checks if a key is present in the dictionary and returns True, otherwise it returns
False.
Traversing a Dictionary:
We can access each item of the dictionary or traverse a dictionary using for loop.
Method 2:
>>>for key,value in dict1.items():
print(key,':',value)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Dictionary Methods in Python
5. get(key, default=None)- Returns the value for a given key. If the key is not found, returns None
(or an optional default value if provided).
6. update(other_dict)- Adds key-value pairs from another dictionary to the current dictionary.
9. popitem()-Removes and returns the last (key, value) pair as a tuple. Useful when you need to pop
items in LIFO order.
10. setdefault(key, default=None)- Returns the value for a key if it exists. If the key is not present,
adds it with the specified default value.
12. fromkeys(seq, value=None)- Creates a new dictionary with keys from the sequence seq and all
values set to value.