Python dictionary (Avoiding Mistakes)
Last Updated :
06 Jul, 2021
What is dict in python ?
Python dictionary is similar to hash table in languages like C++. Dictionary are used to create a key value pair in python. In place of key there can be used String Number and Tuple etc. In place of values there can be anything. Python Dictionary is represented by curly braces. An empty dictionary is represented by {}. In Python dictionary key and values are separated by ':' and key values pair are separated by ', ' . Below example explains it clearly
Example
Python3
# program to understand dictionary in python
# creating an empty dictionary
mydictionary ={}
# inserting values in dictionary
mydictionary ={'name':'Ankit',
'college':'MNNIT',
'address':'Allahabad'};
# print the dictionary
print(mydictionary)
Output :
{'address': 'Allahabad', 'name': 'Ankit', 'college': 'MNNIT'}
where is used ?
Dictionaries gives us power to model a variety of real world applications. We can create a dictionary of person where we can store all information related to that person as name age contact location etc. In dictionaries can be store any type of information such as words and their meaning. Python dictionaries are used very much in machine learning where machine talks with human in that situation some predefined words are stored as keys and their meaning as values and when user want anything that thing is searched in keys if it is found then its value is returned otherwise it shows some error. In fact python dictionary can be used anywhere where hashing is used in normal old language.
Example to understand use of dict
Python3
# program to understand dictionary in python
# creating an empty dictionary
mydictionary ={}
# inserting values in dictionary
mydictionary ={'greeting':'Hello',
'status':'how are you',
'thanks':'thanks visit again'};
# print values according to choice
print(mydictionary['greeting'])
print(mydictionary['status'])
print(mydictionary['thanks'])
Output :
Hello
how are you
thanks visit again
Common mistakes while using dicts and overcomes
Following are some mistake while using dict in python.
1 ) To access element of dictionary in python never direct access element using key name always try to use .get method. If key is not present then .get method would print none while [key] will terminate the whole program.
Python3
# program to understand dictionary in python
# creating an empty dictionary
mydictionary ={}
# inserting values in dictionary
mydictionary ={'greeting':'Hello',
'status':'how are you',
'thanks':'thanks visit again'};
# print values according to choice
print(mydictionary['greeting'])
print(mydictionary['status'])
print(mydictionary['thanks'])
# this will print none
print(mydictionary.get('college'))
# this will throw an error
print(mydictionary['college'])
Output :
Hello
how are you
thanks visit again
None
Runtime Error
Traceback (most recent call last):
File "/home/ce65dd34285f0cb0781de2a068e658fa.py", line 14, in
print(mydictionary['college'])
KeyError: 'college'
2 ) When we want to copy a dictionary to another dictionary then there should be proper knowledge of copying method
- new_dictionary = old_dictionary : This line means that old_dictionary and new_dictionary will refer to same object means that change in one dictionary will reflect to other dictionary.
- new_dictionary = dict(old_dictionary) and new_dictionary = old_dictionary.copy() : will copy old dictionary to new dictionary means that update in old will not reflect update in d but values in e will be copied by using references . This will perform shallow copy
- new_dictionary = copy.deepcopy(old_dictionary) : This will generate an deep copy .
Python3
# program to understand dictionary in python
# creating an empty dictionary
mydictionary ={}
# inserting values in dictionary
mydictionary ={'greeting':'Hello',
'status':'how are you',
'thanks':'thanks visit again'};
# print values according to choice
print(mydictionary['greeting'])
print(mydictionary['status'])
print(mydictionary['thanks'])
# copying dictionary
m = mydictionary
print(m)
Output :
Hello
how are you
thanks visit again
{'greeting': 'Hello', 'status': 'how are you', 'thanks': 'thanks visit again'}
When not to use dicts ?
Python dict are useful in many situation but in some situation their use must be avoided .In python never think that only dictionary are associative array. In dict we should try to store values of same type.
- If we want to search values whether values is present into dictionary or not always use in that situation python set because in python set is an associative array with bool values whether element is present or not.
- For fixed number of attribute always use Class or named tuple in python .
- When you want a predefined message when a particular key then use collections.defaultdict in python
Similar Reads
Python - Access Dictionary items
A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets.Example:Pythona = {"Geeks": 3, "for": 2, "geeks": 1} #Access the value assosiated with "geeks" x = a["geeks"] print
3 min read
Python Dictionary Exercise
Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti
3 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value c
5 min read
How to Add Function in Python Dictionary
Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks
4 min read
Python input() Function
Python input() function is used to take user input. By default, it returns the user input in form of a string.input() Function Syntax: input(prompt)prompt [optional]: any string value to display as input messageEx: input("What is your name? ")Returns: Return a string value as input by the user.By de
4 min read
Precision Handling in Python
Python in its definition allows handling the precision of floating-point numbers in several ways using different functions. Most of them are defined under the "math" module. In this article, we will use high-precision calculations in Python with Decimal in Python.ExampleInput: x = 2.4Output: Integra
6 min read
Interesting facts about Python Lists
Python lists are one of the most powerful and flexible data structures. Their ability to store mixed data types, support dynamic resizing and provide advanced features like list comprehension makes them an essential tool for Python developers. However, understanding their quirks, like memory usage a
6 min read
What is Python? Its Uses and Applications
Python is a programming language that is interpreted, object-oriented, and considered to be high-level. What is Python? Python is one of the easiest yet most useful programming languages and is widely used in the software industry. People use Python for Competitive Programming, Web Development, and
8 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read