38.Dictionaries in Python- Creating Accessing, adding , removing elements

List organize their element by position. This mode of organization is useful when you want to locate the first element, the last element or visit each element in sequence.However, in some situations, the position of datum in a structure is irrelevant and we are interested in its association with some other elements in the structure.For example persons name with phone number.

A dictionary organizes information by association, not position. We can refer to a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps a value. The association of a key and a value is called a key-value pair.
A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences.

Dictionaries are mutable.
Dictionaries are unordered.
Items in dictionaries are accessed via keys and not via their position.
A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. 
The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs.
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.
Dictionaries belong to the built-in mapping type.

Creating Python Dictionary

Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.
An item has a key and a corresponding value that is expressed as a pair (key: value).

While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.

The following is the general syntax for creating a dictionary.
D = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'}
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces {}.
Examples
# empty dictionary 
>>>my_dict = {} 
# dictionary with integer keys 
>>>my_dict = {1: 'apple', 2: 'ball'} 
# dictionary with mixed keys 
>>>my_dict = {'name': 'John', 1: [2, 4, 3]} 
# using dict() 
>>>my_dict = dict({1:'apple', 2:'ball'}) 
# from sequence having each item as a pair 
>>>my_dict = dict([(1,'apple'), (2,'ball')])

Dictionaries can also be created from list. Two List can be combined into a list of tuples using the zip() function.The list can then be converted into a dictionary using dict() function.
>>>L1=[1,2,3]
>>>L2=[10,20,30]
>>> dict(zip(L1,L2))
{1: 10, 2: 20, 3: 30}


Accessing Elements from Dictionary

While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside square brackets [] or with the get() method.

If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

>>>my_dict = {'name': 'Jack', 'age': 26}
>>> print(my_dict['name'])
Jack
>>> print(my_dict['names'])
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    print(my_dict['names'])
KeyError: 'names'
>>> print(my_dict.get('age'))
26
>>> print(my_dict.get('address'))
None

Changing and Adding Dictionary elements

Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.

If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to the dictionary.
>>> my_dict = {'name': 'Jack', 'age': 26}
>>> my_dict['age'] = 27
>>> print(my_dict)
{'name': 'Jack', 'age': 27}
>>> my_dict['address'] = 'Downtown'
>>> print(my_dict)
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

Removing elements from Dictionary

We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value.

The popitem() method can be used to pop out the last item from the dictionary. All the items can be removed at once, using the clear() method.

We can also use the del keyword to remove individual items or the entire dictionary itself.
 
Example

>>> squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> squares.pop(4)
16
>>> print(squares)
{1: 1, 2: 4, 3: 9, 5: 25}

>>> squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> squares.popitem()
(5, 25)
>>> print(squares)
{1: 1, 2: 4, 3: 9, 4: 16}

>>> squares.clear()
>>> print(squares)
{}

>>> squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> del(squares[1])
>>> print(squares)
{2: 4, 3: 9, 4: 16, 5: 25}

this will delete the dictionary 
>>> del squares

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020