- Python Dictionary 42 exercises with solution An editor is available at the bottom of the page to write and execute the scripts. 1. Write a Python script to sort (ascending and descending) a dictionary by value. Go to the editor. Click me to see the sample solution. Write a Python script to add a key to a dictionary. Go to the editor.
- The Headlines hide 1. What is Python dictionary? An example of creating a dictionary 3. Accessing a specific element of dictionary example 4. Using a for loop to iterate through dictionary elements 5. Getting total number of dictionary items example 6. Getting keys of a dictionary by using keys method 7. Accessing only values.
Python Dictionary basically contains elements in the form of key-value pairs. It is an unordered collection of items. Creation of Dictionary. The 'invalid dict' above with list keys is not valid python code - dict keys must be immutable. Therefore you are not comparing dictionaries. Therefore you are not comparing dictionaries. If you try and use a list as a dictionary key your code will not run. You have to iterate the dictionary for printing the values. The for statement will find all the values of the key and print(diskeys) will output all the values of corresponding keys. Related Article. How to convert the dictionary to list in Python? You have a dictionary and you want to convert it into a list.
Tutorials
Dictionary is a built-in Python Data Structure that is mutable. It is similar in spirit to List, Set, and Tuples. However, it is not indexed by a sequence of numbers but indexed based on
keys
and can be understood as associative arrays. On an abstract level, it consists of a key
with an associated value
. In Python, the Dictionary represents the implementation of a hash-table
.What are keys?
As shown in the figure below, keys are immutable ( which cannot be changed ) data types that can be either strings or numbers. However, a key can not be a mutable data type, for example, a list. Keys are unique within a Dictionary and can not be duplicated inside a Dictionary. If it is used more than once, subsequent entries will overwrite the previous value.
Key
connects with the value
, hence, creating a map-like structure. For example, remove keys from the picture; all you are left with is a data structure containing a sequence of numbers. Dictionaries, therefore, hold a key: value
pair at each position.A Dictionary is represented by a pair of curly braces
{}
in which enclosed are the key: value
pairs separated by a comma.Creating a Dictionary
Syntax
As a refresher, here is a recipe for creating a Dictionary:
In the above syntax, both the keys and the values are strings.
Example of Creating a Dictionary
Let's convert the population data to a Dictionary. To create the Dictionary, you will use the curly brackets. Next, inside the brackets, you will have a bunch of key:value pairs. In this case, the keys are country names, and values are the corresponding populations.
The first key is Afghanistan, and its corresponding value is 30.55. Notice the colon that separates the key and value pair. Let's do the same for the other two key:value pairs and store the result in the variable
world
.Now, to find the population for Albania, simply type
world
Sqlpro studio 1 0 164 – powerful database manager tasks. , and then the string Albania inside square brackets. In other words, you pass the key in square brackets and get the corresponding values.This approach is not only intuitive, but it is also very efficient because Python can look up these keys very fast, even for huge dictionaries.
Interactive Example of Creating a Dictionary
In the below example, you will use the strings in
countries
and capitals
, create a Dictionary called europe
with 4 key:value pairs. Here the countries
will be the keys, and capitals
will be the values. Beware of capitalization! Make sure you use lowercase characters everywhere. Finally, print out europe
to see if the result is what you expected.When you run the above code, it produces the following result:
Try it for yourself.
To learn more about dictionaries in Python, please see this video from our course Intermediate Python.
This content is taken from DataCamp’s Intermediate Python course by Hugo Bowne-Anderson.
In this class, you’ll discover what Python Dictionary is and how to create it. You will also learn to append, update, remove and search elements in a dictionary object.
A dictionary in Python is a scrambled collection of objects. Unlike other data types such as a list or a set which has a single value field, the dictionary type stores a key along with its value.
The keys pair with values using a colon (:) while the commas work as a separator for the elements. Also, the entire dictionary object uses curly braces to enclose itself.
Below is an example of a barren dictionary object which doesn’t have any elements.
Please remember that only keys inside a dictionary can’t have duplicates, but their values can repeat themselves.
Next, the value in a dictionary can be of any valid Python data type. But the keys have a constraint to be of any immutable data types such as a string, a number, or a tuple.
Dictionary in Python
Contents
- 4 Append in a Dictionary
- 5 Update a Dictionary
Create Dictionaries
If you wish to create a Python dictionary with fixed keys and values, then it’s quite easy to do so. Just combine all the “key1:value1, key2:value2,…” pairs and enclose with curly braces.
The combination of a key and its value, i.e. “key: value” represents a single element of a dictionary in Python.
While defining static dictionary objects, you must be careful to use unique values for keys. However, they can derive from any valid Python data type.
Also, remember to use only immutable data types for the values while they can have duplicates.
![Python Python](https://www.tutorialgateway.org/wp-content/uploads/Python-Dictionary-items-1.png)
Learn about – Python Strings
Dictionary Operations
Access Elements
Python dictionary has the key as an additional parameter. We can access the elements of a dictionary with the help of keys by using them as Index to the array operator ([]) or passing as Argument to the get() method.
Both methods will work the same, but the former will return a KeyError while the latter returns None if the element is not available.
Running the above coding snippet will result in the following output.
Accessing an element with a non-existent key will return an error. Check out the below code.
The above example uses the “Name” key which doesn’t exist. Running the same would produce a “KeyError.”
In the next example, we’ll access the elements in a Python dictionary using the get() function.
This code will yield the following result.
Append in a Dictionary
You can append a new item to an existing dict object with elements in the following two ways.
Assignment to Append Elements
Update Method to Append Elements
You can call the dictionary’s update method to append a new element to it. We are extending the above example, see below:
Update a Dictionary
Python allowed the dictionary object to be mutable. Hence, the add or update operations are permissible. You can push a new item or modify any existing with the help of the assignment operator.
Whenever you add an element whose key already exists, it’s value will get changed to the new value. On adding a fresh “key: value” pair, a new element will get added to the dictionary.
Use Assignment
In the below example, we are demonstrating both the update and the addition operations on the existing dictionary object.
The execution of the above code will produce the following output.
Use the Update Method
You can alternatively call the update method to modify the value of any existing element. See the example below.
Let’s resume the previous example. It has a dict object which contains a key as ‘Student Name’. We’ll update its value.
Remove Elements
Python lends us a no. of methods to remove elements from the dictionary.
The most common of them is the “pop()” method. It takes the key as the input and deletes the corresponding element from the Python dictionary. It returns the value associated with the input key.
Another method is “popitem()”. It removes and returns a random element (key, value) from the dictionary.
If you like to drop all the elements from the dictionary, then use the “clear()” method to flush everything.
Dictionary Python Methods
Nonetheless, one more way to remove an element from a dictionary is to use the del keyword. It can help you delete individual items and consequently the whole dictionary object.
Here is the result of running the above coding snippet.
In the above example, the second last statement removes all the elements from the Python dictionary, leaving it empty.
And the subsequent call to the “del” operator on the dictionary object removes it altogether. Hence, the last print statement fails with the “NameError.”
Learn about – Tuples in Python
Dictionary Attributes
Python doesn’t impose any constraints on the “Values” of a dictionary object. You can form them using the standard Python or any custom data types. But, as we said earlier, the “Keys” aren’t the same as “Values” and have altogether different handling.
Hence, it is vital for you to memorize the following two facts about the dictionary “Keys.”
- The same key can’t have another value in the dictionary. It confirms that a duplicate key can’t exist. However, even if you try to supply a duplicate key, it’ll only modify the existing key with the value provided in the last assignment.
Executing the above code will show that the key “Student Name” will keep the last assigned value, i.e., “Kerry.”
- Python says that the dictionary Keys should derive from the immutable data types. You can infer that only allowed types are strings, numbers or tuples. Check out a standard example below.
Dictionary Python Example
In the above example, the key is using a list type. Since Python doesn’t support this, hence the statement will generate a “TypeError.”
Here is the outcome of the above example.
Iterate Dictionary
Similar to the lists, you can use a “for in” loop to traverse through a dictionary. In general, it’s the keys which enable iteration.
Let’s understand the concept with a simple example. It prints all the keys of a dictionary in a loop.
The output of the above Python code is as follows.
Follow one more example below which prints keys along with values.
Dictionary Python Get
The result of the above Python code is as follows.
Dictionary Comprehension
Just like a Python list, the dictionary also allows comprehension to create new objects from an iterable in a loop.
You can specify a dictionary comprehension by using an expression including a “key: value” pair followed by for loop and enclosed with curly braces {}.
Follow the below examples to create a dictionary using the comprehension syntax.
Let’s make a dictionary object with the string type for keys and the number format for values.
Another example of creating a dictionary from the list of weekdays as keys and the length of each week as the values.
We can use the “enumerate()” function in a dictionary comprehension. It helps us save the index of a specific element that we could use later. Also, in a for loop, the position of a list element isn’t visible without “enumerate().”
Such Python dictionaries which have element index can be useful in many situations.
Membership Test
We can quickly confirm whether a Key is present in a dictionary or not using the keyword “in.” Also, please note that the membership test is only applicable to Keys, not for Values.
The output of the above snippet is as follows.
Quick wrap up – Python Dictionary
In this tutorial, we covered one of the most significant topics in Python. In whatever domain of Python, you choose to work, knowing dictionaries will surely help.
Now, if you’ve learned something from this lesson, then care to share it with your colleagues. Also, connect to our social media (Facebook/Twitter) accounts to receive timely updates.
Best,
TechBeamers