Python Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair.
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.
Program on Dictionary
mydict = {}
# dictionary with integer keys
mydict = {1: 'apple', 2: 'ball'}
print(mydict)
# dictionary with mixed keys
mydict = {'name': 'prasad', 1: [2, 4, 3]}
print(mydict)
# using dict()
mydict = dict({1:'vision', 2:'computers'})
print(mydict)
# from sequence having each item as a pair
mydict = dict([(1,'python'), (2,'numpy')])
print(mydict)
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.
mydict = {'name': 'prasad', 'age': 50}
print(mydict['name'])
print(mydict.get('age'))
print(mydict.get('address'))
# Trying to access keys which doesn't exist throws error
print(mydict['address'])
Accessing an element of a nested dictionary
# Creating a Dictionary
Dict = {'vis1': {1: 'prasad'},
'vis2': {'Name': 'DG'}}
# Accessing element using key
print(Dict['vis1'])
print(Dict['vis1'][1])
print(Dict['vis2']['Name'])
Adding elements to dictionary
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.
Program on Changing and adding Dictionary Elements
mydict = {'name': 'Prasad', 'age': 50}
print(mydict)
# update value
mydict['age'] = 40
print(mydict)
# add item
mydict['address'] = 'Vuyyuru'
print(mydict)
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 remove and return an arbitrary (key, value) item pair 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.
Program Removing elements from a dictionary
# create a dictionary
sqrs = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
print(sqrs.pop(4))
print(sqrs)
# remove an arbitrary item, return (key,value)
print(sqrs.popitem())
print(sqrs)
# remove all items
sqrs.clear()
print(sqrs)
# delete the dictionary itself
del sqrs
# Throws Error
print(sqrs)
Python Dictionary Methods
Method |
Description |
Removes all items from the dictionary. |
|
Returns a shallow copy of the dictionary. |
|
Returns a new dictionary with keys from seq and value equal to v (defaults to None). |
|
Returns the value of the key. If the key does not exist, returns d (defaults to None). |
|
Return a new object of the dictionary's items in (key, value) format. |
|
Returns a new object of the dictionary's keys. |
|
Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError. |
|
Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. |
|
Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None). |
|
Updates the dictionary with the key/value pairs from other, overwriting existing keys. |
|
Returns a new object of the dictionary's values |
Program on Dictionary Methods
marks = {}.fromkeys(['python', 'java', 'C++'], 0)
print(marks)
for item in marks.items():
print(item)
print(list(sorted(marks.keys())))
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.
Program on Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}
print(odd_squares)
Program on Dictionary Membership Test
# Membership Test for Dictionary Keys
sqrs = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in sqrs)
print(2 not in sqrs)
# membership tests for key only not value
print(49 in sqrs)
Iterating Through a Dictionary
# Iterating through a Dictionary
sqrs = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in sqrs:
print(sqrs[i])
Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks.
Program on Dictionary Built-in Functions
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(all(squares))
print(any(squares))
print(len(squares))
print(sorted(squares))
For
More Explanation
&
Online Classes
More Explanation
&
Online Classes
Contact Us:
+919885348743
+919885348743