Home » Dictionary In Python: A Practical Guide to Optimal Data Handling

Dictionary In Python: A Practical Guide to Optimal Data Handling

Dictionary In Python: A Practical Guide to Optimal Data Handling

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"
}
Python

How 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
}
Python

Dictionaries 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)
Python

Output:

<code>{'name': 'Karan', 'age': 19, 'eligible': True}</code>
Python

Type 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'))
Python

Output:

Karan
True
Python

II. 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())
Python

Output:

dict_values(['Karan', 19, True])
Python

III. 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())
Python

Output:

dict_keys(['name', 'age', 'eligible'])
Python

IV. 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())
Python

Output:

<code>dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])</code>
Python

Adding 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)
Python

Output:

{'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)
Python

Output:

{'name': 'Karan', 'age': 19, 'eligible': True}
{'name': 'Karan', 'age': 20, 'eligible': True, 'DOB': 2001}
Python

Removing 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)
Python

Output:

{}
Python

ii. 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)
Python

Output:

{'name': 'Karan', 'age': 19}
Python

iii. 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)
Python

Output:

{'name': 'Karan', 'age': 19, 'eligible': True}
Python

apart 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)
Python

Output:

{'name': 'Karan', 'eligible': True, 'DOB': 2003}
Python

If 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)
Python

Output:

NameError: name 'info' is not defined
Python

Python 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)
Python

Output:

{'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2003}
Python

Or 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)
Python

Output:

{'name': 'Karan', 'age': 19, 'eligible': True, 'DOB': 2003}
Python

Conclusion

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

Q1. Can Dictionaries Contain Different Data Types?

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 Code
for key in car:
print(key, car[key])