Back to home
Logicmojo - Updated Jan 3, 2023



This tutorial will teach you all you need to know about Python dictionary, including how to construct them, how to access them, how to add and remove entries from them, and how to use the built-in methods.

What is Python Dictionary?

  1. The data is stored in a key-value pair format using Python Dictionary.

  2. In Python, a dictionary is a data type that may replicate a real-world data arrangement in which a specific value exists for a specified key.




  3. The changeable data structure is what it is. The dictionary is made up of two parts: keys and values.
    Keys must be made up of only one element.
    Values can be of any type, including list, tuple, integer, and so on.

  4. To put it another way, a dictionary is a collection of key-value pairs with the value being any Python object. The keys, on the other hand, are immutable Python objects, such as Numbers, text, or tuple.

  5. A colon (:) separates each key from its value, commas divide the elements, and the whole thing is enclosed in curly braces.

  6. Values may not be unique within a dictionary, but keys are.

  7. A dictionary's contents can be any data type, but the keys must be immutable data types like characters, numbers, or tuples.

Note – Polymorphism is not allowed in dictionary keys.

The following features are shared by dictionaries and lists:

  1. Both are subject to change.

  2. Both are active.

  3. They can expand and contract as needed.

  4. They can both be nested.

  5. Another list can be contained within a list.

  6. Another dictionary can be found within a dictionary.

  7. A list can also be found in a dictionary, and vice versa.

The way elements are retrieved in dictionaries differs from how they are accessed in lists:

  1. Indexing is used to access list elements based on their position in the list.

  2. Keys are used to access dictionary components.

Characteristics of Python Dictionary

  1. Ordered :- Dictionaries are ordered, which means that the items are in a specific sequence that will not change. A simple Hash Table is made up of key-value pairs that are sorted in pseudo-random order using the Hash Function calculations.

  2. Mutable :- The dictionaries are changeable collections, which means we may add or remove things after they have been created.

  3. Unique :- As previously stated, each value has a Key; Keys in Dictionaries should be unique. If we store any value with an existing Key, the most current value will overwrite the previous value.




Creating a Dictionary

A Dictionary is built in Python by enclosing a succession of entries in curly braces and separating them with a comma. The Dictionary stores pairs of values, one of which is the Key and the other is the Key:value pair element. In a dictionary, values can be of any data type and can be replicated, but keys cannot be copied and must be immutable.

Note: Dictionary keys are case sensitive, therefore two keys with the same name but different cases will be interpreted differently.


# empty dictionary
dict = {}

# dictionary with integer keys
dict = {1: 'cat', 2: 'dog', 3: 'mouse'}

# dictionary with mixed keys
dict = {'name': 'Priya', 1: [2, 4, 3]}

# using dict()
dict = dict({1: 'cat', 2: 'dog', 3: 'mouse'})

# from sequence having each item as a pair
dict = dict([(1,'cat'), (2,'dog'), (3,'mouse')])

As you can see from the example above, we can also use the built-in dict() function to construct a dictionary.


Example Code :

# Creating a Dictionary
# with Integer Keys
dict = {1: 'cat', 2: 'dog', 3: 'mouse'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
 
# Creating a Dictionary
# with Mixed keys
dict = {'name': 'Priya', 1: [2, 4, 3]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)


Output :

Dictionary with the use of Integer Keys: 
{1: 'cat', 2: 'dog', 3: 'mouse'}

Dictionary with the use of Mixed Keys: 
{'name': 'Priya', 1: [2, 4, 3]}




# Creating a Nested Dictionary
dict = {key1: 'Python', key2: 'Dictionary',
        key3: {'keyA': 'Nested', 'keyB': 'Python', 'keyC': 'Dictionary'}}
print(dict)

Output :

 {key1: 'Python', key2: 'Dictionary', key3: {'keyA': 'Nested', 'keyB': 'Python', 
 'keyC': 'Dictionary'}}                       


Adding elements to a Dictionary

The addition of elements in the Python Dictionary can be done in a variety of ways. Dict[Key] = 'Value' Dict[Key] = 'Value' Dict[Key] = 'Value' Dict[Key] = 'Value' Dict[Key] = 'Value' Dict[Key] = 'Value' Dict[Key] = ' The built-in update() method can be used to update an existing value in a Dictionary. An existing Dictionary can also have nested key values added to it.

Note: If the key-value pair already exists, the value is changed; otherwise, a new Key with the value is created and added to the Dictionary.


Example Code:

# Creating an empty Dictionary
dict = {}
print("Empty Dictionary: ")
print(dict)
 
# Adding elements, single element at a time
dict[0] = 'apple'
dict[2] = 'mango'
dict[3] = 'cat'
dict[4] = 'dog'
print("\nDictionary after adding 4 elements: ")
print(dict)
 
# Adding set of values to a single Key
dict['Value_set'] = 2, 3, 4, 8
print("\nDictionary after adding 5 elements: ")
print(dict)


Output :

Empty Dictionary: 
{}

Dictionary after adding 4 elements: 
{0: 'apple', 2: 'mango', 3: 'cat', 4: 'dog'}

Dictionary after adding 5 elements: 
{0: 'apple', 2: 'mango', 3: 'cat', 4: 'dog', 'Value_set': (2, 3, 4, 8)}

Accessing elements from a Dictionary

To get to the things in a dictionary, look up the key name. Inside square brackets, the key can be utilised.


Example Code:

# Creating a Dictionary
dict = {1: 'orange', 'name': 'rachit', 3: 'grey'}
 
# accessing a element using key
print("Accessing a element using key:")
print(dict['name'])
 
# accessing a element using key
print("Accessing a element using key:")
print(dict[1])


Output :

Accessing a element using key:
rachit

Accessing a element using key:
orange

The get() method in Python provides an alternative to using the get() method to obtain dictionary data. It would produce the same outcome as indexing does.


Example Code:

# Creating a Dictionary
dict = {1: 'orange', 'name': 'rachit', 3: 'grey'}
 
# accessing a element using key
print("Accessing a element using key:")
print(dict.get('name'))
 
# accessing a element using key
print("Accessing a element using key:")
print(dict[=.get(1))


Output :

Accessing a element using key:
rachit

Accessing a element using key:
orange



Learn More

Changing and Adding Dictionary elements

Dictionaries are subject to change. Using the assignment operator, we can create new items or change the value of existing ones.
If the key already exists, the existing value will be changed. If the key is missing, the dictionary is updated with a new (key: value) pair.


Example Code:

# Changing and adding Dictionary Elements
dict = {'name': 'Sonal', 'age': 32}
print(dict)
# update value
dict['age'] = 34
print(dict)

# add item
dict['address'] = 'Agra'
print(dict)


Output :

{'name': 'Sonal', 'age': 32}
{'name': 'Sonal', 'age': 34}
{'name': 'Sonal', 'age': 34, 'address': 'Agra'}

Removing elements from Dictionary

Using del keyword :

The del keyword can be used to delete keys from a Python Dictionary. Specific dictionary values, as well as the entire dictionary, can be erased using the del keyword. Items in a nested dictionary can also be deleted using the del keyword and a specified nested key and key to be deleted from that nested Dictionary.

Note: Because the del Dict deletes the entire dictionary, printing it after it has been deleted will result in an Error.


Example Code:

# Initial Dictionary
dict = {'name': 'Sonal', 'age': 34, 'address': 'Agra'}
print(dict)

# deleting element
del dict['age'] 
print(dict)


Output :

{'name': 'Sonal', 'age': 34, 'address': 'Agra'}
{'name': 'Sonal', 'address': 'Agra'}

Using pop() method :

The Pop() function returns and deletes the value of the provided key.


Example Code:

# Initial Dictionary
dict = {'name': 'Sonal', 'age': 34, 'address': 'Agra'}
print(dict)

# deleting element
dict.pop('address') 
print(dict)


Output :

{'name': 'Sonal', 'age': 34, 'address': 'Agra'}
{'name': 'Sonal', 'age': 34}

Using popitem() method :

The popitem() function returns and deletes an arbitrary key-value pair from the dictionary.


Example Code:

# Initial Dictionary
dict = {'name': 'Sonal', 'age': 34, 'address': 'Agra'}
print(dict)

# deleting arbitary element
dict.popitem() 
print(dict)


Output :

{'name': 'Sonal', 'age': 34, 'address': 'Agra'}
{ 'age': 34, 'address': 'Agra'}

Using clear() method :

The clear() method can be used to delete all elements from a dictionary at once.


Example Code:

# Initial Dictionary
dict = {'name': 'Sonal', 'age': 34, 'address': 'Agra'}
print(dict)

# deleting dictionary
dict.clear() 
print(dict)


Output :

{'name': 'Sonal', 'age': 34, 'address': 'Agra'}
{}

Properties of Dictionary Keys

There are no constraints on dictionary values. They can be any type of Python object, including standard and user-defined objects. The same cannot be said for the keys.
When it comes to dictionary keys, there are two things to keep in mind.

🚀 Multiple entries per key are not permitted. That is to say, no duplicate keys are permitted. When there are duplicate keys during an assignment, the last assignment wins.
Example Code:

# Dictionary
dict = {'name': 'Sonal', 'age': 34, 'age': 36}
print(dict['age'])


Output :

36

🚀Immutable keys are required. This means that you can use strings, numbers, or tuples as dictionary keys, but you can't use ['key'].


Dictionary Methods

The methods that can be used with a dictionary are listed below. Some of these have already been mentioned in the previous paragraphs.


FunctionsDescription
copy() They return a shallow copy of the dictionary with the copy() method.
clear() The clear() method clears the dictionary of all elements.
pop() Takes an element from a dictionary with the specified key and returns it.
popitem() Returns a tuple after removing an arbitrary key-value pair from the dictionary.
get() It's a standard way of getting a value for a key.
dictionary name.values() The function dictionary name.values() returns a list of all the values in a dictionary.
str() Returns a dictionary's printable string representation.
update() Adds the key-value pairs from dict2 to dict.
setdefault() If key is not already in dict keys, setdefault() sets dict[key]=default ().
dict() Returns a list of the keys in the dictionary dict ().
items() Returns a collection of dict tuple pairs (key, value).
has key() Returns true if the key exists in the dictionary dict, false otherwise
fromkeys() Make a new dictionary with seq's keys and value's values.
type() The type of the supplied variable is returned by type().
cmp() compares both dicts' elements.


Operators and Built-in Functions

Many of the operators and built-in functions that may be used with strings, lists, and tuples are already familiar to you. Some of these are also compatible with dictionaries.
The in and not in operators, for example, return True or False depending on whether the provided operand appears as a dictionary key.

All(), any(), len(), cmp(), sorted(), and other built-in functions are widely used with dictionaries to complete various tasks.

Built-in FunctionsDescription
all() TIf all keys in the dictionary are True, all() returns True (or if the dictionary is empty).
any() If any key in the dictionary is true, any() returns True. Return False if the dictionary is empty.
len() len() returns the dictionary's length (the number of items).
cmp() cmp() is a function that compares items from two dictionaries. (Python 3 doesn't have this feature.)
sorted() Return a new sorted list of dictionary keys.


Restrictions on Dictionary Keys

  1. In Python, almost any value can be used as a dictionary key. Built-in objects like as types and functions can also be used. There are, however, a few limitations that dictionary keys must adhere to.

  2. For starters, a key can only appear once in a dictionary. There are no duplicate keys allowed. Because a dictionary maps each key to its matching value, it's pointless to map the same key many times.

  3. When you apply a value to an already existing dictionary key, it replaces the existing value rather than adding the key again.

  4. Similarly, if you supply a key a second time during dictionary formation, the second occurrence will take precedence over the first.
    Second, a dictionary key must be of an immutable type. Several of the immutable types you're familiar with—integer, float, string, and Boolean—have already been used as dictionary keys in examples.

  5. Because tuples are immutable, they can also be used as dictionary keys. (Recall from the tuple explanation that one reason for choosing a tuple rather to a list is that there are times when an immutable type is essential.) One of them is this.)

  6. Because lists and dictionaries are both mutable, neither a list nor another dictionary may serve as a dictionary key.


Restrictions on Dictionary Values

Dictionary values, on the other hand, are unrestricted. There aren't any at all. Any type of object that Python supports can be used as a dictionary value, including mutable types like lists and dictionaries, as well as user-defined objects, which you will learn about in future lectures.

There are no restrictions on a single value appearing many times in a dictionary.



Building a Dictionary Incrementally

If you know all the keys and values ahead of time, defining a dictionary with curly brackets and a list of key-value pairs, as shown above, is fine. But what if you need to quickly create a dictionary?

Begin by constructing an empty dictionary, which is indicated by empty curly braces. Then, one by one, you can add new keys and values. Once the dictionary has been formed in this manner, its values can be accessed in the same way that any other dictionary's values can be accessed. An additional index or key is required to retrieve the values in the sublist or subdictionary. Because there are few restrictions on the keys and values that can be used, dictionaries can be used for a wide range of purposes.

Crack your next tech interview with confidence!

Conclusion

The essential aspects of the Python dictionary were discussed in this tutorial, as well as how to access and alter dictionary data.
The most commonly used Python types are lists and dictionaries. They have some similarities, as you can see, but they differ in how their elements are accessed. Dictionary entries are accessed by key, while list members are accessed by number index based on order.
Because of this distinction, lists and dictionaries are best used in different situations. You should now be able to tell which, if either, is the better option for a particular case.
Following that, you'll learn about Python sets. The set is a composite data type that is distinct from both the list and the dictionary.