Python DictionaryAn effective data structure for storing data in Python is dictionaries, in which can simulate the real-life data arrangement where some specific value exists for some particular key.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be of any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple. Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally unordered. Creating the DictionaryThe simplest approach to create a Python dictionary is by using curly brackets {}, but there are other methods as well. The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {}, and each key is separated from its value by the colon (:). The syntax to define the dictionary is given below. Syntax: In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of an immutable object. Let's see an example to create a dictionary and print its content. Code Output <class 'dict'> printing Employee data .... {'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'} Python provides the built-in function dict() method which is also used to create the dictionary. The empty curly braces {} is used to create empty dictionary. Code Output Empty Dictionary: {} Create Dictionary by using dict(): {1: 'Microsoft', 2: 'Google', 3: 'Facebook'} Dictionary with each item as a pair: {4: 'Praneeth', 2: 'Varma'} Accessing the dictionary valuesWe've discussed about using indexing to access data stored in lists and tuples. However, because the dictionary's keys are distinct from one another, it is possible to get the values by utilising the keys. The dictionary values can be accessed in the following way. Code Output <class 'dict'> printing Employee data .... Name : David Age : 30 Salary : 55000 Company : GOOGLE Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result as given by the indexing. Adding Dictionary ValuesThe dictionary is a mutable data type, and its values can be updated by using the specific keys. The value can be updated along with key Dict[key] = value. The update() method is also used to update an existing value. Note: If the key-value already present in the dictionary, the value gets updated. Otherwise, the new keys added in the dictionary.Let's see an example to update the dictionary values. Example - 1:Code Output Empty Dictionary: {} Dictionary after adding 3 elements: {0: 'Peter', 2: 'Joseph', 3: 'Ricky'} Dictionary after adding 3 elements: {0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)} Updated key value: {0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)} Example - 2:Code Output <class 'dict'> printing Employee data .... {'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'} Enter the details of the new employee.... Name: Rahul Age: 28 Salary: 36000 Company:Microsoft printing the new data {'Name': 'Rahul', 'Age': 28, 'salary': 36000, 'Company': 'Microsoft'} Deleting Elements using del KeywordThe items of the dictionary can be deleted by using the del keyword as given below. Code Output <class 'dict'> printing Employee data .... {'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'} Deleting some of the employee data printing the modified information {'Age': 30, 'salary': 55000} Deleting the dictionary: Employee Lets try to print it again NameError: name 'Employee' is not defined The last print statement in the above code, it raised an error because we tried to print the Employee dictionary that already deleted. Deleting Elements using pop() MethodThe pop() method accepts the key as an argument and remove the associated value. Consider the following example. Code Output {1: 'JavaTpoint', 3: 'Website'} Python also provides a built-in methods popitem() and clear() method for remove elements from the dictionary. The popitem() removes the arbitrary element from a dictionary, whereas the clear() method removes all elements to the whole dictionary. Iterating DictionaryA dictionary can be iterated using for loop as given below. Example 1Code Output Name Age salary Company Example 2Code Output John 29 25000 GOOGLE Example - 3Code Output John 29 25000 GOOGLE Example 4Code Output ('Name', 'John') ('Age', 29) ('salary', 25000) ('Company', 'GOOGLE') Properties of Dictionary Keys1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key. Consider the following example. Code Output Name John Age 29 Salary 25000 Company GOOGLE In [ ]: 2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as the key, but we cannot use any mutable object like the list as the key in the dictionary. Consider the following example. Code Output Traceback (most recent call last): File "dictionary.py", line 1, in Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"} TypeError: unhashable type: 'list' Built-in Dictionary FunctionsA technique that may be used on a construct to produce a value is known as a function. Additionally, it doesn't change the construct. A Python dictionary can be used with a handful of the methods that Python provides. The built-in python dictionary methods along with the description are given below.
Python's len() method returns the dictionary's length. Each key-value pair lengthens the string by one. Code Output 4
The any() method returns True indeed if one dictionary key does have a Boolean expression of True, much like it does for lists and tuples. Code Output True
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True Boolean value. Code Output False
The sorted() method returns an ordered series of the dictionary's keys, much like it does with lists as well as tuples. The initial Python dictionary is not changed by the ascending sorting. Code Output [ 1, 5, 7, 8] Built-in Dictionary methodsThe built-in python dictionary methods along with the description and Code are given below.
It is used to delete all the items of the dictionary. Code Output { }
It returns a shallow copy of the dictionary. Code Output {1: 'Microsoft', 2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
eliminates the element using the defined key. Code Output {2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'} popitem() removes the most recent key-value pair entered Code Output {1: 'Microsoft', 2: 'Google', 3: 'Facebook'}
It returns all the keys of the dictionary. Code Output dict_keys([1, 2, 3, 4, 5])
It returns all the key-value pairs as a tuple. Code Output dict_items([(1, 'Microsoft'), (2, 'Google'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])
It is used to get the value specified for the passed key. Code Output
It updates the dictionary by adding the key-value pair of dict2 to this dictionary. Code Output {1: 'Microsoft', 2: 'Google', 3: 'TCS'}
It returns all the values of the dictionary. Code Output dict_values(['Microsoft', 'Google', 'TCS']) Built-in Dictionary methodsThe built-in python dictionary methods along with the description are given below.
Next TopicPython Functions
|