Dictionary in Python is a built-in data type that is used to store elements in the form of key:value pairs. Value is said to be mapped with the key and you can extract the value by passing the mapped key. Dictionaries are indexed by keys and dictionaries in Python are mutable just like list in Python.
- Creating a dictionary
- Retrieving value in dictionary
- Retrieving value in nested dictionary
- Retrieving value using get method in dictionary
- Adding new key:value pair
- Updating value for an existing key
- Removing element from Dictionary
- Getting the count of items in a dictionary
- Rules for keys in the dictionary
- Methods in Python dictionary
Creating a dictionary
1. You can create dictionary by storing elements with in curly braces {}. Elements here are comma separated key:value pairs. Each key:value pair has colon ( : ) in between.
Syntax
d = { key1: value1, key2: value2, . . . keyn: valuen }
Here are some examples of creating dictionary.
#empty dictionary d = {} print(d) #{} #dictionary with int as key and string as value d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'} # nested dictionary- Each value is another dictionary d = {'1001':{'id':1001, 'name':'Ram', 'age': 43}, '1002':{'id':1002, 'name':'Chaya', 'age': 34}} print(d) #{'1001': {'id': 1001, 'name': 'Ram', 'age': 43}, '1002': {'id': 1002, 'name': 'Chaya', 'age': 34}}
2. You can also create a dictionary using the dict() constructor by passing a sequence of key-value pairs.
Syntax
d = dict([ (key1, value1), (key2, value2), . . . (keyn: valuen) ])
Here are some examples of creating dictionary using dict() constructor.
d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')]) print(d) # {1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}
When the keys are simple strings, you can also specify pairs using keyword arguments.
d = dict(NDL='New Delhi', KOL='Kolakata', MUM='Mumbai', HYD='Hyderabad') print(d) # {'NDL': 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'}
Python 3.7 onward, dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary.
Retrieving value in dictionary
Once dictionary is created you can access any value by passing the mapped key.
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} val = d[1] print(val) # Ashish
As you can see by passing key 1 you get the mapped value 'Ashish'
d = dict(NDL='New Delhi', KOL='Kolkata', MUM='Mumbai', HYD='Hyderabad') print(d['KOL']) #Kolkata
If you pass any key which is not present in the dictionary, Python raises KeyError exception.
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} val = d[10] print(val)
Output
Traceback (most recent call last): File d:\netjs\netjs_2017\python\pythonnewws\mydictionary.py:9 val = d[10] KeyError: 10
Retrieving value in nested dictionary
You can retrieve value from the nested dictionary by passing respective keys in square brackets.
For example-
d = {'1001':{'id':1001, 'name':'Ram', 'age': 43}, '1002':{'id':1002, 'name':'Chaya', 'age': 34}}
Here we have nested dictionary mapped with each key. If we want to retrieve name as 'Ram' then we first have to pass key as '1001' to get the mapped value. Since value is again a dictionary so we need to pass another key as 'name' to get the mapped value.
d['1001']['name']
Retrieving value using get method in dictionary
In the previous example we have seen that passing a key that is not present in the dictionary results in KeyError. If you want to avoid that you can use get method which has the following syntax.
get(key, default=None)
Method returns the value for key if key is in the dictionary, else default. If default value is not passed, it defaults to None, so that this method never raises a KeyError.
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} val = d.get(10, 'Not Found') print(val) #Not Found
Adding new key:value pair
Adding new key:value pair to the dictionary is done by assigning value to a respective key.
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} # new key:value d[5] = 'Esha' print(d) # {1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh', 5: 'Esha'}
Updating value for an existing key
If you want to update value for an existing key that can be done by assigning value to that key.
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} #changed value for key=3 d[3] = 'Chirag' print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chirag', 4: 'Dinesh'}
Removing element from Dictionary
A key:value pair can be removed from a dictionary using del
statement.
d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')]) print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'} del(d[2]) print(d) #{1: 'Ashish', 3: 'Chandan', 4: 'Dinesh'}
There is also a pop(key[,default])
method in dictionary which removes the key if it is in the dictionary and
returns its value, else returns default. If default is not given and key is not in the dictionary, a KeyError is raised.
d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')]) print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'} print(d.pop(2)) #Bhavya print(d) #{1: 'Ashish', 3: 'Chandan', 4: 'Dinesh'}
Getting the count of items in a dictionary
You can get the count of items in a dictionary using len() function.
len(d)- Returns the count of items in the dictionary d.
d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')]) print(len(d)) #4
Rules for keys in the dictionary
Dictionary in Python has certain rules for keys.
1. Key should be immutable. You can use any datatype as key which is immutable like strings and numbers. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key.
This restriction is there because immutable datatypes are hashable. Dictionary is a HashTable based data structure which uses key to calculate a hash value to determine where to store the mapped value. For retrieval hash value of the passed key is calculated to determine the location of the value.
In the example code one of the keys is a list.
code = ['NDL'] city = {code: 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'} print(city)
Output
File d:\netjs\netjs_2017\python\pythonnewws\mydictionary.py:9 city = {code: 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'} TypeError: unhashable type: 'list'
2. Keys in a dictionary should be unique, if you pass the same key again that doesn't result in an error but overwrites the previous value.
In the example code key 3 is duplicate.
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh', 3:'Chirag'} print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chirag', 4: 'Dinesh'}
Methods in Python dictionary
Some of the operations supported by dictionaries in Python.
1. clear()- Used to remove all items from the dictionary.
d = dict(NDL='New Delhi', KOL='Kolkata', MUM='Mumbai', HYD='Hyderabad') print(d) #{'NDL': 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'} d.clear() print(d) #{}
2. items()- Returns a view object that contains each key:value pair as a tuple in a list.
d = dict(NDL='New Delhi', KOL='Kolkata', MUM='Mumbai', HYD='Hyderabad') print(d.items()) #dict_items([('NDL', 'New Delhi'), ('KOL', 'Kolkata'), ('MUM', 'Mumbai'), ('HYD', 'Hyderabad')])
3. keys()- Returns a view object of the dictionary's keys.
d = dict(NDL='New Delhi', KOL='Kolkata', MUM='Mumbai', HYD='Hyderabad') print(d.keys()) # dict_keys(['NDL', 'KOL', 'MUM', 'HYD'])
4. pop()- Removes an element from the dictionary for the passed key and returns the value.
d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')]) print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'} print(d.pop(2)) #Bhavya print(d) #{1: 'Ashish', 3: 'Chandan', 4: 'Dinesh'}
5. popitem()- Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order Python 3.7 onward, before that it used to remove a random element.
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'} print(d.popitem()) #(4, 'Dinesh') print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan'}
6. setdefault(key, default=None)- Method returns the values of the key if it is present in the dictionary. If key is not present in the dictionary then inserts key with a value of default and returns default.
In the following code there is no change in the dictionary.
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'} print(d.setdefault(3, 'Chirag')) #Chandan print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}
With the following code a new item is added to the dictionary.
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'} print(d.setdefault(5, 'Esha')) #Esha print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh', 5: 'Esha'}
7. update(other)- This method is used to merge dictionary with other dictionary. While merging if the same key is present in other then it overwrites the existing key's value.
names = {4:'Divya', 5:'Esha'} d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'} print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'} print(names) #{4: 'Divya', 5: 'Esha'} d.update(names) print(d) # {1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Divya', 5: 'Esha'}
8. values()- Returns a view object of the dictionary's values.
city = {'NDL': 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'} print(city.values())
Output
dict_values(['New Delhi', 'Kolkata', 'Mumbai', 'Hyderabad'])
That's all for this topic Dictionary in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment