Dictionary
Similar to maps in C++ or HashMap in Java, the dictionary in Python is the collection of key : value pairs.
As seen in the diagram above, words are our keys, and their meanings are our values.
It is an ordered collection, i.e., if you add a new key : value pair, it will be placed at the end, and it does not allow duplicates.
Creating a dictionary
We can create the dictionary by using curly braces {}.
Syntax :
dictionary_name = {}
Example :
myDict = {}
print(myDict)
Output:
{}
We can place the key : value pairs inside curly braces {} separated by commas.
Example :
myDict = {
"Cpp" : "maps",
"Python" : "Dictionary",
10 : "ten",
"sum" : 1,
"isTrue" : False
}
print(myDict)
Output:
{'Cpp': 'maps', 'Python': 'Dictionary', 10: 'ten', 'sum': 1, 'isTrue': False}
We can also use the inbuilt dict() constructor to create a dictionary.
Syntax:
dictionary_name = dict(key1 = value1, key2 = value2, ...)
Example:
myDict = dict(Python = "Dictionary",
Java = "HashMaps",
num = 10,
isTrue = False)
print(myDict)
Output:
{'Python': 'Dictionary', 'Java': 'HashMaps', 'num': 10, 'isTrue': False}
Accessing an Element
If we have the key, then we can access the values mapped with that key by using the following syntax:
dictionary_name[key]
Example :
myDict = {"Cpp" : "maps", "Python" : "Dictionary","JAVA" : "HashMap"}
print(myDict["Cpp"])
Output:
maps
To access all the keys, values, and key : value pairs use the inbuilt keys(), values(), and items() functions, respectively.
Example:
myDict = {"Cpp" : "maps", "Python" : "Dictionary","JAVA" : "HashMap"}
print(myDict.keys())
print(myDict.values())
print(myDict.items())
Output
dict_keys(['Cpp', 'Python', 'JAVA'])
dict_values(['maps', 'Dictionary', 'HashMap'])
dict_items([('Cpp', 'maps'), ('Python', 'Dictionary'), ('JAVA', 'HashMap')])
You can practice by yourself with the help of online python compiler for better understanding.
Adding a new item
Python dictionaries are mutable, i.e., we can add a new item or remove an item after creating the dictionary.
We can use an inbuilt function called update to add a new key : value pair.
Syntax:
dictionary_name.update({key : value})
Example:
myDict = {"Cpp" : "maps", "Python" : "Dictionary","JAVA" : "HashMap"}
myDict.update({"JavaScript" : "Maps"})
print(myDict)
Output:
{'Cpp': 'maps', 'Python': 'Dictionary', 'Java': 'HashMaps', 'JavaScript': 'Maps'}
Ordered Collection
The dictionary in Python remembers the order in which items are inserted.
Let's try to understand it by example -
myDict = {}
myDict.update({"Cpp" : "maps"})
myDict.update({"Python" : "Dictionary"})
myDict.update({"JAVA" : "HashMap"})
print(myDict)
output:
{'Cpp': 'maps', 'Python': 'Dictionary', 'JAVA': 'HashMap'}
As seen in the example, the items are maintained in the order of insertion.
Removing an item
Like the update function, Python also provides an in-built del() function to remove an item.
Syntax:
del(dictionary_name[key])
Example:
myDict = {"Cpp" : "maps", "Python" : "Dictionary","JAVA" : "HashMap", "JavaScript": "Maps"}
del(myDict["Cpp"])
print(myDict)
Output:
{'Python': 'Dictionary', 'Java': 'HashMaps', 'JavaScript': 'Maps'}
Using the del function, we can also delete the entire dictionary.
Syntax:
del(dictionary_name)
Example:
myDict = {"Cpp" : "maps", "Python" : "Dictionary","JAVA" : "HashMap", "JavaScript": "Maps"}
del(myDict)
print(myDict)
Output:
NameError: name 'myDict' is not defined
Length Of Dictionary
To determine the number of key : value pairs in the dictionary, we can use the len() function.
Syntax:
len(dictionary_name)
Example:
myDict = {"Cpp" : "maps", "Python" : "Dictionary","JAVA" : "HashMap"}
print(len(myDict))
Output:
3
Nested Dictionary
Such a dictionary in which value mapped with one of the keys is another dictionary is known as a nested dictionary.
Example
myDict = { 'a' : 'A',
'b' : 'B',
'c' : {'d' : 'D', 'e' : 'E', 'f' : 'F'}}
print(myDict)
Output:
{'a': 'A', 'b': 'B', 'c': {'d': 'D', 'e': 'E', 'f': 'F'}}
Sets
Python's set is another built-in data type. Unlike dictionary, it is an unordered collection, and it does not allow duplicates. Similar to the dictionary, sets are also mutable, i.e., we can add or remove the elements after the declaration, but the elements inside the sets are immutable, i.e., once inserted, we can't modify it.
Creating a set
Like the dictionary, we can create the set using curly braces and place the elements inside the curly braces separated by commas.
Syntax
set_name = {}
Example
mySet = {'India', 'c', False, 120, 1}
print(mySet)
Output
{False, 1, 'India', 'c', 120}
We can also use the inbuilt set() constructor to create a set.
Syntax
Set_name = set([element1, element2, element3, ......])
Example
mySet = set(['Inida', 'U.S.A', False, 1])
print(mySet)
Output
{False, 1, 'U.S.A', 'India'}
Adding an element
To add an element, use the inbuilt add() function.
Syntax:
set_name.add(element)
Example:
mySet = {"U.S.A", 1}
mySet.add("India")
mySet.add(False)
print(mySet)
Output:
{False, 1, 'India', 'U.S.A'}
Removing an element
We can use the inbuilt remove() function to remove an element from the set.
Syntax:
set_name.remove(element)
Example:
mySet = set(['India', 'U.S.A', False, 1])
mySet.remove('U.S.A')
print(mySet)
Output:
{False, 1, 'India'}
Length Of the set
We can find the number of elements in the set by using the len() function.
Syntax
len(set_name)
Example
mySet = set(['India', 'U.S.A', False, 1])
print(len(mySet))
Output
4
Accessing the elements in the set
Python's sets are the unordered collection, so we can't access its elements by referring to an index or key, but we can loop through the elements it contains using for loop or while loop.
Example
mySet = set(['India', 'U.S.A', False, 1])
for element in mySet:
print(element)
Output:
False
U.S.A
India
1
Duplicates are not allowed
Set in Python does not allow duplicates. If we try to add an element that is already present in the set, the set will not change, and if we try to add duplicates during declaration, the set will simply discard them.
Example:
mySet = set(('India', 'U.S.A', False, 1, False))
print(mySet)
mySet.add(False)
print(mySet)
Output:
{'U.S.A', False, 'India', 1}
{'U.S.A', False, 'India', 1}
You can also read about Internal Working of HashMap here.
Must Read: entryset java