Python Dictionary With Examples

Python Dictionary is similar to map from other languages (Java/Scala) that is used to store key:value pair. It is a built-in data type in Python. Unlike sequences, which are indexed by numbers, dictionaries are indexed by keys, which can be any immutable type such as strings, and numbers(int, float). Tuples can be used as keys if they contain only strings and numbers.

In this article, I will explain Python dictionary with examples, how to create dictionaries, accessing elements, add and removing elements from dictionaries. Also, you will learn various inbuilt methods.

Python Dictionary Key Points –

  • Dictionary is used to store data values in key: value pairs.
  • Dictionary is a collection that is unordered and does not allow duplicates.
  • Dictionary is a mutable type so, you can add, remove and update values.
  • Can access dictionary elements by using these methods such as keys(), values(), items().
  • Dictionaries are iterable objects, so Python allows for loops or dictionary comprehensions.
  • Delete all the key: value pairs from the dictionary using clear() method.

Table of contents

  1. What is a dictionary
  2. Syntax of dictionary
  3. Properties of dictionary keys
  4. Access elements of Python dictionary
  5. update & add Python dictionary elements
  6. Delete elements from the dictionary
  7. Iterate dictionary using for loop
  8. Methods of Python dictionary
  9. Dictionary comprehension
  10. Python dictionary functions

1. What is Python Dictionary

A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key: value pair separated by commas. The dictionaries are indexed by keys.

Moreover, dictionaries are mutable data types, which means that you can be added, deleted, and updated their key:value pairs.

A value can be any data type such as a number(int, float), a string, a list, a tuple, or even another dictionary and it allows duplicates. On the other hand, keys are an immutable type such as string, numbers(int, float), and tuple and it doesn’t allow duplicates. In case, you add duplicates, which will update the existing keys of the Python dictionary.

2. Syntax of Dictionary

Python dictionary is a collection of key, value pairs enclosed with {}, each key and its corresponding value separated by a colon (:).


# Syntax of the dictionary
courses = { "course":"python",
         "fee":4000,
         "duration"="30 days"}

From the above, courses is a dictionary, which contains key-value pairs inside the{ }. Here the keys are course, fee and duration.

Let’s see how to create empty dictionary.


# Create an empty dictionary
courses={}
print(courses)

#{}

Now, let’s see different ways to create Python Dictionaries.


# Create dictionary with integer keys
courses={1:'java',2:'python',3:'panda'}
print(courses)

# create dictionary using dict()method
courses=dict({1:'java',2:'python',3:'panda'})
print(courses)

# Creating dictionary in which each item as a Pair 
courses=dict([(1,'java'),(2,'python'),(3,'panda')])
print(courses)  

# All above examples yields below output.
#{1: 'java', 2: 'python', 3: 'panda'}

3. Properties of Python Dictionary Keys

There are two important points of Python dictionary

  • It doesn’t allow duplicates in Keys. In case, you add duplicates, which will update the existing keys of the Python dictionary.
  • The values in the dictionary can be of any type, while the keys must be immutable like numbers(int, float), tuples, or strings. Otherwise, the new keys will add to the dictionary.

4. Accessing the Python Dictionary Elements

As we know, how we access data in the list and tuple by using index. Similarly, the values can access in the dictionary by using the keys. Python provides two different ways of using a key to access the values of the dictionary, which are inside square brackets [] or with the get() method.


# Access values from dictionary using keys
my_dict = {'course':'python','fee':4000,'duration':'60days'}
print(my_dict['course'])
# Output 
#python

print(my_dict['fee'])
# Output
#4000

# Access values from dictionary using get() method
print(my_dict.get('duration'))
# Output
#60days

5. Updating & Adding Dictionary Elements

As we know from the above, dictionaries are mutable. which means that you can be added, deleted, and updated their key: value pairs. For instance,


# Updating and adding dictionary elements
my_dict = {'course':'python','fee':4000,'duration':'60 days'}

# Add element
my_dict['tutor']='Richerd'
print(my_dict)

# Updating existing key of dictionary
my_dict['duration']='45 days'
print(my_dict)

Yields below output


{'course': 'python', 'fee': 4000, 'duration': '60 days', 'tutor': 'Richerd'}
{'course': 'python', 'fee': 4000, 'duration': '45 days', 'tutor': 'Richerd'}

update() method is used for updating the dictionary using another dictionary or an iterable of key-value pairs(such as a tuple). If the key is already present in the dictionary update() method updates the existing key with key-value pair.


# Updating the dictionary using update() method
my_dict = {'course':'python','fee':4000,'duration':'60 days'}
my_dict.update({'discount':2000})
print("updated MyDict:", my_dict)

# updating existing key of the dictionary
my_dict.update({'discount': 1000})
print("updated MyDict:", my_dict)

# Outputs:
updated MyDict: {'course': 'python', 'fee': 4000, 'duration': '60 days', 'discount': 2000}
updated MyDict: {'course': 'python', 'fee': 4000, 'duration': '60 days', 'discount': 1000}

6. Deleting Elements from Python Dictionary

Python provides several methods for deleting elements from the dictionary.

  • Using the pop() method we can delete a particular element in a dictionary. the pop() method allows key as an argument and deletes the corresponding value.
  • The popitem() method allows deleting arbitrary elements from the dictionary and return(key, value).
  • At a time all the elements can be deleted using the clear() method.
  • The elements of the dictionary can be deleted using the del keyword. Using the del keyword to delete a single element or whole dictionary itself.

Let’s take an examples for better understanding


# Create a dictionary
My_dict={'course': 'python', 'fee': 4000, 'duration': '60 days', 'tutor': 'Richerd'}

# Delete particular key and returns its value using pop()
print(my_dict.pop('duration'))
# Output: 60 days
print(my_dict)
# Output: {'course': 'python', 'fee': 4000, 'tutor': 'Richerd'}

# Delete an arbitrary element using popitem() return (key, value)
my_dict={'course': 'python', 'fee': 4000, 'duration': '60 days', 'tutor': 'Richerd'}
print(my_dict.popitem())
# Output: ('tutor', 'Richerd')
print(my_dict)
# Output: {'course': 'python', 'fee': 4000, 'duration': '60 days'}

Elements of the dictionary can be deleted using del keyword, clear() method. For instance,


# Create a dictionary   
my_dict={'course': 'python', 'fee': 4000, 'duration': '60 days', 'tutor': 'Richerd'}
print(type(my_dict))
# Output: 

# Delete fee element using del keyword
del my_dict['fee']
print(my-dict)
# Output: {'course': 'python', 'duration': '60 days', 'tutor': 'Richerd'}

# Delete whole dictionary
del my_dict
print(my_dict)
# Output: 
NameError: name 'my_dict' is not defined

# Delete all elements using clear()
my-dict.clear()
print(my_dict)
# Output: {}

7. Iterate Python Dictionary Using For Loop

Using a for loop we can iterate a dictionary. There are multiple ways to iterate and get the key and values from dict. Iterate over keys, Iterate over key and value. I will cover these with examples below.

7.1 For Loop Through by Dict Keys

By default, if you use the examples explained above, you will get one key from the dict for each iteration.


# Loop through by Dict Keys
my_dict={"Course":"python","Fee":4000,"Duration":"60 days"}
for x in my_dict:
    print(x)
 

Yields below output. Notice that it just displayed the keys from the dict.


Course
Fee
Duration

7.2 Loop Through by Key &Value

items() method which returns a view object that gives a list of dictionary’s (key, value) tuple pairs. You can iterate over tuple to get the key and value.


# Loop through by Key and Value
my_dict ={"Course":"python","Fee":4000,"Duration":"60 days"}
for key, value in my_dict.items():
    print(key, value)

Yields below output


Course python
Fee 4000
Duration 60 days

7.3 Use key to Get the Value

Use dict[key] to get the value of the key.


# Use key to get the Value
my_dict ={"Course":"python","Fee":4000,"Duration":"60 days"}
for key in my_dict:
    print(key, my_dict[key])

Yields below output.


Course python
Fee 4000
Duration 60 days
5

7.4 Use dict.keys() & dict.values()

You can also use keys() method and iterate over each key. Similarly, you can use the values() method and iterate each value of Python dictionary.


# Use dict.keys() & dict.values()
my_dict ={"Course":"python","Fee":4000,"Duration":"60 days"}
for key in my_dict.keys():
    print('Key: '+ key)
for value in my_dict.values():
    print('Value: '+value)

Yields below output.


Key: Course
Key: Fee
Key: Duration
Value: python
Value: 4000
Value: 60 days

8. Python Dictionary methods

Python provides various inbuilt methods to operate on a dictionary, below are some of those methods.

MethodDescription
clear()Delete all the key: value pairs from the dictionary
copy()Returns a shallow copy of the dictionary
fromkeys()creates a new dictionary from the given iterable objects
get()Returns the value of the specified key
items()Returns a view object that allows a dynamic view of dictionary elements as a list of key, value (tuple) pairs.
keys()Returns a view object which contains a list of all keys related to the dictionary.
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()It returns a value if the key is present. Otherwise, it inserts the key with the default value into the dictionary. The default value of the key is None.
update()Updates the dictionary with the specified key-value pairs
values()Returns a view object that contains a list of all the values stored in the dictionary.

9. Python Dictionary comprehension

Python Dictionary comprehension is an efficient and concise way to create dictionaries using iterables. Moreover, it is same as a list comprehension but the syntax is different due to the structure of dictionaries.

9.1 Syntax of the dictionary comprehension


# Syntax of the dictionary comprehension
{key: value for variable in iterable(if conditional)}

9.2 How to build a dictionary using dictionary comprehension


# Create dictionary using dictionary comprehension
my_dict = {n: n**2 for n in range(10)}
print(my_dict)

# Output:
 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

9.3 How to Modify Dictionaries Using Dictionary Comprehension

We can access the key-value pairs in a dictionary by using the items() method. It returns list of tuples(key- value) pairs.

We can use the elements of an existing Python dictionary as iterable in dictionary comprehension. It provides us to create the dictionaries based on existing dictionaries.


# Convert the numbers squares to cubes by using dict comprehension 
my_squares = {1:1,2:4,3:9,4:16,5:25}
my_cubes = {key: value*key for (key, value) in my_squares.items()}
print(my_cubes)

# Outputs:
 {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

Here, we can observe that we have converted the numbers in the form of squares to cubes in very short code this much of possible we owned that by using dictionary comprehension.

10. Python Dictionary Built-In Functions

Now we have sufficient knowledge about how to work with Python dictionaries, let’s take a look at some dictionary functions.

cmp(), len(),str(), type() are Python dictionary built-in functions. Which are commonly used with dictionaries to perform various tasks.

SNFunctionDescription
1cmp(dict1, dict2)It compares the items of both the dictionary and returns true if the first dictionary values are greater than the second dictionary, otherwise it returns false.
2len(dict)It is used to get the length of the dictionary.
3str(dict)It converts the dictionary into the printable string representation.
4type(variable)It is used to get the type of the passed object.

11. cmp()

The compare function cmp() is used to compare values and keys of two dictionaries in Python. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.

cmp() is not supported in Python 3.

12. len()

Python len() function is used to get the total length of the dictionary, this is equal to the number of items in the dictionary. This method acts as a counter which is automatically defined the data. Dictionaries in Python are a collection of key-value pairs, this is one of the most important data structures in Python.

12.1 Syntax of len() Function

Following is the syntax of the len() function.


# Syntax of the len()
len(dict)

12.2 Parameters of len()

The len() allows a single parameter which is iterable object.

12.3 Return Value of len()

len() function returns the number of iterable items given in the Python dictionary.

12.4 Usage of len()

len() function always returns the number of iterable items given in the Python dictionary.


# Get the length of the dictionary using len()
my_dict ={'course': 'python', 'fee': 4000, 'duration': '60 days', 'tutor': 'Richard'}
length=len(my_dict)
print("Length Of the dictionary:", length)

# Outputs:
Length of the dictionary: 4

13. str()

This method is used to return the string, denoting all the dictionary keys with their values.

13.1 Syntax of str() Function

Following is the syntax of str() function of dictionary.


# Syntax of str() function
str(dict)

13.2 Parameters of str() Function

This function allows one parameter that is dictionary.

13.3 Return Value of str()

This function returns string representation.

13.4 Usage of str() Dictionary Function


# create dictionary
my_dict = { 'course' : 'Python', 'fee' : 4000 }
# using str() to display dict as string
print ("The components of a dictionary are a string :",str(my_dict))

# Outputs:
The components of a dictionary are a string : {'course': 'Python', 'fee': 4000}

14. type()

Python dictionary method type() returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.

Two different types of arguments can be passed to type() function, single and three argument. If single argument type(obj) is passed, it returns the type of given object. If three arguments type(name, bases, dict) is passed, it returns a new type object.

14.1 Syntax

Following is the syntax of type() function


# syntax of type() function
type(dict)

14.2 Parameters of type()

This function allows one parameter which is a dictionary.

14.3 Return value of type()

This method returns the type of the passed variable.

14.4 Usage of Python Dictionary type()

Python dictionary method type() returns the type of the passed variable.


# create dictionary
my_dict = { 'course' : 'Python', 'fee' : 4000 }
# using type() to display dict type
print ("The type of passed object :",type(my_dict))

# Outputs:
The type of passed object :  

15. Conclusion

In this article, I have explained dictionary is a data structure similar to a map in other languages that are used to store key-value pairs. Also covered how to create a Python dictionary, accessing elements, add and remove elements from dictionaries. Also, I have explained various inbuilt methods and inbuilt functions.

Happy Learning !!

References

python dictionary

Leave a Reply

You are currently viewing Python Dictionary With Examples