Python DictionaryDictionaries are a useful data structure for storing data in Python because they are capable of imitating real-world data arrangements where a certain value exists for a given key. The data is stored as key-value pairs using a Python dictionary.
A dictionary is, in other words, a group of key-value pairs, where the values can be any Python object. The keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers. Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally unordered. Creating the DictionaryCurly brackets are the simplest way to generate a Python dictionary, although there are other approaches as well. With many key-value pairs surrounded in curly brackets and a colon separating each key from its value, the dictionary can be built. (:). The following provides the syntax for defining the dictionary. 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': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS} 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: 'Hcl', 2: 'WIPRO', 3: 'Facebook'} Dictionary with each item as a pair: {4: 'Rinku', 2: 'Singh'} Accessing the dictionary valuesTo access data contained in lists and tuples, indexing has been studied. The keys of the dictionary can be used to obtain the values because they are unique from one another. The following method can be used to access dictionary values. Code Output ee["Company"]) Output <class 'dict'> printing Employee data .... Name : Dev Age : 20 Salary : 45000 Company : WIPRO 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 utilising the right keys allows you to change its values. Dict[key] = value and the value can both be modified. An existing value can also be updated using the update() method. Note: The value is updated if the key-value pair is already present in the dictionary. Otherwise, the dictionary's newly added keys.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 .... Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter the details of the new employee.... Name: Sunny Age: 38 Salary: 39000 Company:Hcl printing the new data {'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'} 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': 'WIPRO'} 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() MethodA dictionary is a group of key-value pairs in Python. You can retrieve, insert, and remove items using this unordered, mutable data type by using their keys. The pop() method is one of the ways to get rid of elements from a dictionary. In this post, we'll talk about how to remove items from a Python dictionary using the pop() method. The value connected to a specific key in a dictionary is removed using the pop() method, which then returns the value. The key of the element to be removed is the only argument needed. The pop() method can be used in the following ways: Code Output {1: 'JavaTpoint', 3: 'Website'} Additionally, Python offers built-in functions popitem() and clear() for removing dictionary items. In contrast to the clear() method, which removes all of the elements from the entire dictionary, popitem() removes any element from a 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 WIPRO Example - 3Code Output John 29 25000 WIPRO Example 4Code Output ('Name', 'John') ('Age', 29) ('salary', 25000) ('Company', 'WIPRO') 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 WIPRO 2. The key cannot belong to any mutable object in Python. Numbers, strings, or tuples can be used as the key, however mutable objects like lists cannot be used as the key in a dictionary. Consider the following example. Code Output Traceback (most recent call last): File "dictionary.py", line 1, in Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIPRO",[100,201,301]:"Department ID"} TypeError: unhashable type: 'list' Built-in Dictionary FunctionsA function is a method that can be used on a construct to yield a value. Additionally, the construct is unaltered. A few of the Python methods can be combined with a Python dictionary. The built-in Python dictionary methods are listed below, along with a brief description.
The dictionary's length is returned via the len() function in Python. The string is lengthened by one for each key-value pair. Code Output 4
Like how it does with lists and tuples, the any() method returns True indeed if one dictionary key does have a Boolean expression that evaluates to True. 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
Like it does with lists and tuples, the sorted() method returns an ordered series of the dictionary's keys. The ascending sorting has no effect on the original Python dictionary. 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 mainly used to delete all the items of the dictionary. Code Output { }
It returns a shallow copy of the dictionary which is created. Code Output {1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
It mainly eliminates the element using the defined key. Code Output {2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'} popitem() removes the most recent key-value pair entered Code Output {1: 'Hcl', 2: 'WIPRO', 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, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])
It is used to get the value specified for the passed key. Code Output
It mainly updates all the dictionary by adding the key-value pair of dict2 to this dictionary. Code Output {1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}
It returns all the values of the dictionary with respect to given input. Code Output dict_values(['Hcl', 'WIPRO', 'TCS']) Next TopicPython Functions |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India