explain dictionary in python
Answers
Dictionary in python have a "key" and a "value of the key".That is, python dictionaries are the collection of key:value pairs.
THANKYOU☺
Heya friend,
Here we go :
Definition :
Python dictionary is an unordered collection of items where each item is a key - value pair. Dictionary can also be considered as a mapping between a set of keys/indices and set of values.
==================================
Important features :
- Each key map to a value. The association of a key and a value is called a key - value pair.
- Each key is separated from it's value by a colon (:) , the items are separated by commas, and the entire dictionary is enclosed in curly braces {} .
- Keys are unique within a dictionary while values may not be.
- The value of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers or tuples.
- Dictionary is mutable. We can add new items or change the value of existing items.
==================================
Creating a dictionary :
A dictionary can be created by placing the items (i.e. the key - value pair) inside curly braces {} separated by comma.
Syntax:
<dictionary_name> = {'key1' : 'value1' , 'key2' : 'value2' , 'key3' : 'value3' ,'keyn' : 'valuen' }
Example:
d = {'manav' : 'python' , 'manav1' : 'dictionary' , 'manav2' : 'tuple'}
==================================
Methods to create a dictionary:
> To create an empty dictionary
d1 = {}
print(d1)
{}
> To create a dictionary directly using curly braces
d2 = {'A' : '1' , 'B' : '2' , 'C' : '3' }
print(d2)
{'A' : '1' , 'B' : '2' , 'C' : '3' }
> To create a dictionary using dict() function
d3=dict()
print(d3)
{}
==================================
Accessing elements in a dictionary
[ To access dictionary elements, we can use square brackets along with the key to obtain it's value ]
d = {'A' : '1' , 'B' : '2' , 'C' : '3' }
print(d['A'])
1
Now, if we give a command like :
d = {'A' : '1' , 'B' : '2' , 'C' : '3' }
print(d['A'])
KEY ERROR [Because the key is not a part of the dictionary]
==================================
List of functions which can be used in a dictionary :-
- len () - calculates number of key-value pair in a dictionary.
- clear() - removes all items from a dictionary.
- get() method - returns the value for a given key, if key is not available, it then returns the default value None.
- items() - gives the content of dictionary as a list of tuples having key - value pairs enclosed within round braces ().
- keys() - returns list of key in a dictionary enclosed within round braces ().
- values() - returns list of value in a dictionary enclosed within round braces ().