Dictionary In Python are powerful data structures that allow you to store and manipulate data in key-value pairs. In this guide, we’ll provide a straightforward explanation of dictionaries, explore common questions, and conclude with insights on their significance.
What are Python Dictionarie?
Dictionaries in Python are collections of key-value pairs. They provide a way to store and access data using unique keys, similar to a real-world dictionary where words (keys) have definitions (values).
Example:
Imagine a phone book where each name (key) is associated with a phone number (value). In Python, this can be represented as a dictionary:
phone_book = {
"Alice": "123-456-7890",
"Bob": "987-654-3210",
"Charlie": "555-555-5555"
}
PythonHow to Create a Dictionary in Python
To create a dictionary in Python, enclose key-value pairs within curly braces {}
, separated by commas.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
PythonDictionaries are ordered collection of data items. They store multiple items in a single variable. Dictionaries items are key-value pairs that are separated by commas and enclosed within curly brackets {}.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
PythonOutput:
<code>{'name': 'Karan', 'age': 19, 'eligible': True}</code>
PythonType of Accessing Dictionary in Python
I. Accessing single values:
Values in a dictionary can be accessed using keys. We can access dictionary values by mentioning keys either in square brackets or by using get method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info['name'])
print(info.get('eligible'))
PythonOutput:
Karan
True
PythonII. Accessing multiple values:
We can print all the values in the dictionary using values() method.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.values())
PythonOutput:
dict_values(['Karan', 19, True])
PythonIII. Accessing keys:
We can print all the keys in the dictionary using keys() method in python.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.keys())
PythonOutput:
dict_keys(['name', 'age', 'eligible'])
PythonIV. Accessing key-value pairs:
We can print all the key-value pairs in the dictionary using items() method in python.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info.items())
PythonOutput:
<code>dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])</code>
PythonAdding Items in Dictionary in Python
There are two ways to adding items to a dictionary in python.
- Create a new key and assign a value to it
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
info['DOB'] = 2001
print(info)
PythonOutput:
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2001}
Python- Use the update() method
The update() method updates the value of the key provided to it if the item already exists in the dictionary, else it creates a new key-value pair.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
print(info)
info.update({'age':20})
info.update({'DOB':2001})
print(info)
PythonOutput:
{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 20, 'eligible': True, 'DOB': 2001}
PythonRemoving Items from Dictionary in Python
There are a few methods that we can use to remove items from dictionary.
i. clear()
The clear() method removes all the items from the list.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.clear()
print(info)
PythonOutput:
{}
Pythonii. pop()
The pop() method removes the key-value pair whose key is passed as a parameter.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True}
info.pop('eligible')
print(info)
PythonOutput:
{'name': 'Karan', 'age': 19}
Pythoniii. popitem()
The popitem() method removes the last key-value pair from the dictionary.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
info.popitem()
print(info)
PythonOutput:
{'name': 'Karan', 'age': 19, 'eligible': True}
Pythonapart from these three methods, we can also use the del keyword to remove a dictionary item.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info['age']
print(info)
PythonOutput:
{'name': 'Karan', 'eligible': True, 'DOB': 2003}
PythonIf key is not provided, then the del keyword will delete the dictionary entirely.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
del info
print(info)
PythonOutput:
NameError: name 'info' is not defined
PythonPython Dictionary copy() method
We can use the copy() method to copy the contents of one dictionary into another dictionary.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
newDictionary = info.copy()
print(newDictionary)
PythonOutput:
{'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2003}
PythonOr we can use the dict() function to make a new dictionary with the items of original dictionary.
Example:
info = {'name':'Karan', 'age':19, 'eligible':True, 'DOB':2003}
newDictionary = dict(info)
print(newDictionary)
PythonOutput:
{'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2003}
PythonConclusion
Python dictionaries are versatile and efficient data structures for organizing and accessing data in key-value pairs. They offer a convenient way to represent complex relationships and are widely used in various programming tasks. By understanding dictionaries and their functionalities, you gain a powerful tool for managing and manipulating data in your Python programs. Embrace dictionaries as a fundamental part of your programming toolkit, and leverage their capabilities to build more efficient and expressive Python applications.
Frequently Asked Questions
Ans: Yes, both keys and values in dictionaries can be of any data type, including strings, numbers, lists, or even other dictionaries.
Q2. What Happens if I Try to Access a Key That Doesn’t Exist?
Ans: If you try to access a key that doesn’t exist, Python will raise a KeyError exception. To avoid this, you can use the get() method or check if the key exists using the in keyword.
Q3. Can I Iterate Over Dictionaries?
Ans: Yes, you can loop through dictionaries using a for loop to access keys, values, or key-value pairs.
Python Codefor key in car:
print(key, car[key])