0% found this document useful (0 votes)
14 views

Dictionary in Python

Helpful it is

Uploaded by

manu1202manu123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Dictionary in Python

Helpful it is

Uploaded by

manu1202manu123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Dictionaries in Python:

The data type dictionary fall under mapping. It is a mapping between a set of keys and a set of values. The key-
value pair is called an item. A key is separated from its value by a colon : and consecutive items are separated by
commas. Items in dictionaries are unordered, so we may not get back the data in the same order in which we had
entered the data initially in the dictionary.

Creating a Dictionary:

To create a dictionary, the items entered are separated by commas (,) and enclosed in curly braces {}.
Each item is a key value pair, separated through colon (:). The keys in the dictionary must be unique and should
be of any immutable data type, i.e., number, string or tuple. The values can be repeated and can be of any data
type.

#dict1 is an empty Dictionary created


>>> dict1 = {}
>>> dict1
{}
#dict2 is an empty dictionary created using built-in function
>>> dict2 = dict()
>>> dict2
{}
#dict3 is the dictionary that maps names of the students to #respective
marks in percentage
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85}
Accessing Items in a Dictionary:

We have already seen that the items of a sequence (string, list and tuple) are accessed using a technique called
indexing.

The items of a dictionary are accessed via the keys rather than their relative positions or indices.

Each key serves as the index and maps to a value.

The following example shows how a dictionary returns the value corresponding to the given key:

>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


>>>dict3['Ram']
89
>>>dict3['Sangeeta']
85
#the key does not exist
>>>dict3['Shyam']
KeyError: 'Shyam'
Dictionaries are Mutable:

Dictionaries are mutable which implies that the contents of the dictionary can be changed after it has been created.

Adding a new item:

We can add a new item to the dictionary as shown in the following example:

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


>>>dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Meena': 78}

Modifying an Existing Item:

The existing dictionary can be modified by just overwriting the key-value pair.

Example to modify a given item in the dictionary:

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


#Marks of Suhel changed to 93.5
>>>dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,'Sangeeta': 85}
Membership Operation:

The membership operator in checks if a key is present in the dictionary and returns True, otherwise it returns
False.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


>>> 'Suhel' in dict1
True

Traversing a Dictionary:

We can access each item of the dictionary or traverse a dictionary using for loop.

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}


Method 1:
>>>for key in dict1:
print(key,':',dict1[key])
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85

Method 2:
>>>for key,value in dict1.items():
print(key,':',value)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Dictionary Methods in Python

1. dict()- Creates a dictionary from a sequence of key-value pairs.

pair1 = [('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)]


dict1 = dict(pair1)
print(dict1)
# Output: {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}

2. keys()-Returns a list of keys in the dictionary.

dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}


print(dict1.keys())
# Output: dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta'])

3. values()-Returns a list of values in the dictionary.

dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}


print(dict1.values())
# Output: dict_values([95, 89, 92, 85])

4. items()-Returns a list of tuples (key-value pairs) in the dictionary.

dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}


print(dict1.items())
# Output: dict_items([('Mohan', 95), ('Ram', 89), ('Suhel',
92), ('Sangeeta', 85)])

5. get(key, default=None)- Returns the value for a given key. If the key is not found, returns None
(or an optional default value if provided).

dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}


print(dict1.get('Sangeeta'))
# Output: 85
print(dict1.get('Sohan', "Not Found"))
# Output: "Not Found"

6. update(other_dict)- Adds key-value pairs from another dictionary to the current dictionary.

dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}


dict2 = {'Sohan': 79, 'Geeta': 89}
dict1.update(dict2)
print(dict1)
# Output: {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Sohan':
79, 'Geeta': 89}

7. clear()- Deletes all items from the dictionary, leaving it empty.

dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}


dict1.clear()
print(dict1)
# Output: {}
8. pop(key, default=None)- Removes and returns the value for the specified key. If the key is not
found, returns None (or an optional default value).

dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}


print(dict1.pop('Ram'))
# Output: 89
print(dict1)
# Output: {'Mohan': 95, 'Suhel': 92, 'Sangeeta': 85}

9. popitem()-Removes and returns the last (key, value) pair as a tuple. Useful when you need to pop
items in LIFO order.

dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}


print(dict1.popitem())
# Output: ('Sangeeta', 85)

10. setdefault(key, default=None)- Returns the value for a key if it exists. If the key is not present,
adds it with the specified default value.

dict1 = {'Mohan': 95, 'Ram': 89}


print(dict1.setdefault('Suhel', 92))
# Adds 'Suhel' with value 92
print(dict1)
# Output: {'Mohan': 95, 'Ram': 89, 'Suhel': 92}

11. copy()- Creates a shallow copy of the dictionary.

dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92}


dict_copy = dict1.copy()
print(dict_copy)
# Output: {'Mohan': 95, 'Ram': 89, 'Suhel': 92}

12. fromkeys(seq, value=None)- Creates a new dictionary with keys from the sequence seq and all
values set to value.

keys = ['a', 'b', 'c']


new_dict = dict.fromkeys(keys, 0)
print(new_dict)
# Output: {'a': 0, 'b': 0, 'c': 0}

You might also like