Dictionary in Python
Dictionary in Python
In some programming languages, dictionaries are often referred to as associative arrays or hash maps. But In Python, a dictionary is a built-in data structure that allows you to store a collection of key-value pairs. Each key in a dictionary is unique and associated with a specific value.
Python Dictionary
Key:value pairs are contained in the dictionary as an unordered collection enclosed in curly brackets ‘{ }’ and separated by commas ‘ , ‘. When the key is known, dictionaries are designed to retrieve values quickly.
Dictionaries are versatile and widely used in Python for tasks that involve mapping keys to values, such as storing configuration settings, caching data, and more.
Creating a Dictionary
A dictionary can be made by enclosing a list of key-value pairs in curly braces ‘{ }’ and separating them with commas. A colon ‘ : ‘ is used to separate each key-value pair.
Code 1:
# Creating a Dictionary dict = { "name": "PrepInsta", "city": "Noida" } print(dict)
Output :
{'name': 'PrepInsta', 'city': 'Noida'}
Accessing the Values
You can access the values in a dictionary by using the keys as the index.
Code 2 :
#Accessing Value dict = { "name": "PrepInsta", "city": "Noida" } print(dict['name'])
Output :
PrepInsta
Modifying Values
You can change the value associated with a key in a dictionary by simply assigning a new value to that key.
Code 3 :
#Modifying Values dict = { "name": "PrepInsta", "city": "Noida" } dict["city"] = "New York" print(dict)
Output :
{'name': 'PrepInsta', 'city': 'New York'}
Adding New Key – Value Pair
Code 4 :
#Adding new key value pair dict = { "name": "PrepInsta", "city": "Noida" } dict["category"] = "edtech" print(dict)
Output :
{'name': 'PrepInsta', 'city': 'Noida', 'category': 'edtech'}
Removing Key – Value Pair
By following the key you want to delete with the del keyword, you can delete key-value pairs from a dictionary.
Code 5 :
#Removing key value pair dict = { "name": "PrepInsta", "city": "Noida" } del dict["city"] print(dict)
Output :
{'name': 'PrepInsta'}
Checking if a Key Exists
You can check if a key exists in a dictionary using the in keyword.
Code 6 :
#Checking if a key exists dict = { "name": "PrepInsta", "city": "Noida" } if "name" in dict: print("Yes, This is in your dictionary")
Output :
Yes, This is in your dictionary
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment