Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Dictionary
1.1.
Creating a dictionary
1.2.
Accessing an Element
1.3.
Adding a new item
1.4.
Ordered Collection
1.5.
Removing an item
1.6.
Length Of Dictionary
1.7.
Nested Dictionary
2.
Sets
2.1.
Creating a set
2.2.
Adding an element
2.3.
Removing an element
2.4.
Length Of the set
2.5.
Accessing the elements in the set
2.6.
Duplicates are not allowed
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024

Dictionary and Sets

gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

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

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

FAQs

Q1. How the dictionary and set are implemented in Python??

The dictionary and sets in Python are implemented using the data structure known as HashTables.

Q2. What is the time complexity of remove() and del() functions??

The worst-case time complexity of the del() function is O(N), where N is the current size of the dictionary and the time complexity of the set.remove() function is O(1) due to the hashtable implementation.

Q3. In a nested dictionary, can we use another map as a key??

Dictionaries in Python are mutable, while keys are immutable, so we can't use the dictionary as a key. 

 

Key Takeaways

In this article, we discussed dictionary and sets in Python and saw their basic functions and implementations. Python is a high-level language that witnessed incredible growth and popularity. Nowadays, it is used by many tech giants and is also used in AI/ML. To learn more about Python, check out this course on coding ninjas.

Also check out - Data Dictionary In Software Engineering

To read more such articles, Coding Ninjas Studio is a one-stop destination. This platform will help you to improve your coding techniques and give you an overview of interview experiences in various product-based companies.

Happy learning!

 

Previous article
Arrays in Python
Next article
Methods of Dictionary
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass