Dictionaries in Python.


Dictionaries:

A dictionary is a mutable data type that stores mappings of unique keys to values. A dictionary is an unordered sequence of key-value pairs. Indices in a dictionary can be of any immutable type and are called keys. Key and value in key-value pairs in dictionary are separated by a colon. Further key: value in the dictionary are separated by commas and are enclosed between curly parentheses.

Note:
Keys value must be unique.
Value may be duplicate.

For example: Here's a dictionary that stores elements and their atomic numbers.

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}



Dictionaries can have keys of any immutable type, like integers or tuples, not just strings. It's not even necessary for every key to have the same type! We can look up values or insert new values in the dictionary using square brackets that enclose the key.

print(elements["helium"])  # print the value mapped to "helium"
elements["lithium"] = 3  # insert "lithium" with a value of 3 into the dictionary



Post a Comment

0 Comments