Dictionaries
Represents a group of elements arranged in the form of key-value pairs. The key and its value are separated by a colon, Unordered mutable collection of key-value pairs .
Creating Dictionaries
1. Initializing dictionary- all the key:value pairs of a dictionary are written collectively
2. Adding key:value pairs to an empty dictionary
3. Creating a dictionary from name:value pairs
(i) Specify key:value pairs as keyword arguments to dict() function
(ii) Specify comma separated key:value pairs
(iii) Specify keys separately and corresponding values separately
(iv) Specify key:value pairs separately in the form of sequence
Accessing elements of a dictionary
While in lists, the elements are accessed through their index, in dictionaries elements are accessed through their keys.
A dictionary operation that takes a key and finds the corresponding value is called lookup.
Attempting to access a key that does not exist causes an error.
As Python dictionaries are unordered, key order is not guaranteed in Python.
Keys act like indexes to access values from a dictionary.
Accessing Keys or Values Simultaneously
<dictionary>.keys() : method to view all keys in one go
<dictionary>.values() : method to view all values in one go
Characteristics of a Dictionary
Dictionaries like lists are mutable and that is the only similarity they have with lists. Otherwise, dictionaries are different types of data structures with following characteristics.
1.Unordered Set
A dictionary is an unordered set of key:value pairs. Its value can contain references to any type of object .You cannot tell the order or position of the key:value pairs in a dictionary there is no index associated.
2.Not a sequence
Unlike a string, list and tuple, a dictionary is not a sequence because it is an unordered set of elements. The sequences are indexed by a range of ordinal numbers. Hence, they are ordered, but a dictionary is an unordered collection.
3.Indexed by Keys,Not Numbers
Dictionaries are indexed bike keys. According to python, a key can be “any non table type”. Since strings and numbers are not mutable you can use them as a key in a dictionary. And if a tuple contains immutable objects such as integers or strings etc., then only it can also be used as a key. But the values in a dictionary can be of any type, and types can be mixed within one dictionary.
4. Keys must be Unique
Each of the keys within a dictionary must be unique. Since keys are used to identify values in a dictionary, there cannot be duplicate keys in a dictionary. However, two unique keys can have same values.
5.Dictionaries are Mutable
Like lists, dictionaries are also mutable. We can change the value of a certain key “in place” using the assignment statement as per syntax
<dictionary>[< key>] = <value>
6.Internally Stored as Mapping
Internally, the key:value pairs of a dictionary are associated with one another with some internal functions (called hash-functions). This way of linking is called mapping.