Anyone Can Code.
Mapping in Python refers to mapping keys and values. To do so, we have a data type known as a dictionary. In a regular dictionary, you can search for the meaning of a certain word by looking for that word. In a Python dictionary, you can create key-value pairs to extract data by using a key as an index.
A dictionary is a collection of data values that is unordered, changeable and indexed. Dictionaries are again similar to lists and tuples but follow a different system. They have 'keys' and 'values' and they are written using curly brackets. The values are assigned to the keys within the dictionary using colons and each key-value pairing is separated using a comma.
Unlike lists and tuples, the elements of a dictionary can be accessed by referring to the key name and placing the key name inside square brackets, similar to indexing with index values. You cannot, however, use indices to access elements of a dictionary.
dict_name = {'name': 'Jyotirmay', 'age': 16, 'organization': 'Q-Programming'} print(dict_name) print(dict_name['organization']){'name': 'Jyotirmay', 'age': 16, 'organization': 'Q-Programming'} Q-Programming
Dictionaries are mutable and he values of a specific key-value pairing can be changed by referring to the key name.
dict_name = {'name': 'Jyotirmay', 'age': 16, 'organization': 'Q-Programming'} dict_name['name'] = 'Jyotirmay Zamre' print(dict_name){'name': 'Jyotirmay Zamre', 'age': 16, 'organization': 'Q-Programming'}
You can also add key-value pairs as so:
dict_name = {'name': 'Jyotirmay', 'age': 16, 'organization': 'Q-Programming'} dict_name['language'] = 'English' print(dict_name){'name': 'Jyotirmay', 'age': 16, 'organization': 'Q-Programming', 'language': 'English'} Q-Programming
You can use any data type for a value, but keys must always be strings. A good programming practice is to use meaningful key names. Another good practice is to keep each key-value pair in a separate line to make your program readable. It just looks better.
That's it for this tutorial! Click Next to access the next tutorial!
This site uses cookies to improve your experience as well as for site metrics. To see more, check out our Privacy Policy