Mapping/Dictionaries in Python
A dictionary is a special data type that is a mapping between a set of keys and a set of values. In Python, a dictionary can be created by placing a sequence of elements within curly { } braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable. The dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing it in curly braces{}.
Syntax:- Dictionaryname={key:value}
Example:
- dict1={“comp”: “computer”, “sci”: “science”}
print(dict1)
print(type(dict1))
Result:
{‘comp’: ‘computer’, ‘sci’: ‘science’}
<class ‘dict’>
- dict3 = {‘name’: ‘john’, ‘code’: 6734, ‘dept’: ‘sales’}
print (dict3) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
Result:
{‘dept’: ‘sales’, ‘code’: 6734, ‘name’: ‘john’}
[‘dept’, ‘code’, ‘name’]
[‘sales’, 6734, ‘john’]
In the above example, we have created a dictionary named dict3.
Here,
- Keys are ‘dept’, ‘code’, ‘name’
- Values are ‘sales’, 6734, ‘john’
Access Dictionary Values Using Keys:
We use keys to retrieve the respective value. In order to access the items in a dictionary, refer to its key name. Keys can be used inside square brackets. For example:
dict1 = {
“brand”: “Ford”,
“electric”: False,
“year”: 1964,
“colors”: [“red”, “white”, “blue”]
}
print(dict1[‘brand’])
print(disc1[‘colors’])
print(type(disc1))
Result:
Ford
[‘red’, ‘white’, ‘blue’]
<class ‘dict’>
In the above example, we are accessing the values of a dictionary by referring to their keys. In the first line we are referring to ‘Ford’ using the ‘brand’ key, then we are referring to [‘red’, ‘white’, ‘blue’] using the ‘color’ key.