Understanding The Python Dictionary Methods

Did You Know The Python Dictionary Methods?
Did You Know The Python Dictionary Methods?

Introduction

A dictionary can be viewed as a collection of key: value pairs with the constraint that the keys must be unique. Dictionaries are also known as “associative arrays” or “maps” in other programming languages like C++ and Java. Unlike arrays, dictionaries are indexed by keys rather than numbers.

The built-in dictionary implementation in Python also contains some useful methods for working with dictionaries. This article provides all the Python dictionary methods along with their implementation.

Let’s first get a brief overview of the dictionary in Python.


Python Dictionary

Dictionaries are one of the fundamental data structures in Python. A dictionary can hold an arbitrary number of objects, each of which is identified by a distinct dictionary key. 

Some of the points regarding dictionaries are given below.

  • Keys are case sensitive, i.e. “NAME” and “name” are two different keys.
  • Maps, hashmaps, lookup tables, and associative arrays are other names for dictionaries. 

  1. Ordered: It implies that the items are placed in a specific sequence that will not change. Dictionary follows the insertion order.

Note: Python 3.6 introduced the order-preserving aspect of the dictionary, which is also applicable to subsequent versions. Earlier dictionaries were unordered collections; you can refer to the official documentation for detailed information.

  1. Mutable: Dictionaries are mutable, which means that after they’ve been created, we can modify, add, or remove items.
  1. No Duplicates: Since items are accessed using their key. There can’t be two items with the same key in a dictionary.

Creating Dictionary

There are two basic ways to create a dictionary in python.

  • Using curly braces
  • Using dict()constructor

Method-1

An empty dictionary is created by a pair of braces {}.
Example D1 = {}

D1 = {}
print(D1)

Output
{}

2. A simple dictionary can be created by placing items inside curly braces {} separated by commas.

Example D2 = {“Name”: “Elon Musk”, “Age”: 42} 

D2 = {"Name": "Elon Musk", "Age": 42} 
print(D2)

Output
{'Name': 'Elon Musk', 'Age': 42 }

Method-2

The in-built dict()constructor can also be used to create a dictionary.
Example D3 = dict(India=91, China=86, Bhutan=975)

D3 = dict(India=91, China=86, Bhutan=975)
print(D3)

Output
{'India': 91, 'China': 86, 'Bhutan': 975}

2. The dict() constructor also builds dictionaries directly from sequences of key-value pairs.
Example – D4= dict([(‘India’, 91), (‘China’, 86), (‘Bhutan’, 975)])

D4 = dict([('India', 91), ('China', 86), ('Bhutan', 975)])
print(D4)

Output
{'India': 91, 'China': 86, 'Bhutan': 975}

Dictionary Methods

METHODS FOR ACCESSING CONTENT

Python dictionary provides built-in methods to access elements, keys and values of a dictionary. Some of the Python dictionary methods to access contents are given below:

  1. Using [ ] brackets: By using keys inside the square brackets we can access the corresponding value in a dictionary.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975}  
print(("Accessing element using [ ] :",D1['China'])

#Output
Accessing element using [ ] : 86

2.

  1. get(): To access the value corresponding to a key in the dictionary, the get() method is used. If the key is not available, it returns the default value, “None”.

It takes two parameters:

  1. Key
  2. Value(optional)

If the specified key is not found, then the passed value will be returned.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975}  
out=D1.get("China")
print("Output of get() method:",out)


#Output
Output of get() method: 86

3. items(): To access all the key-value pairs present in the dictionary, the items() method is used. It returns a list of (key, value) pairs.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
print(D1.items())

#Output
dict_items([('India', 91), ('China', 86), ('Bhutan', 975)])

4. keys(): To get all the keys present in the dictionary, the keys() method is used. It returns a list of keys.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
print(D1.keys())

#Output
dict_keys(['India', 'China', 'Bhutan'])

5. values(): To get all the values present in the dictionary, the keys() method is used. It returns a list of values.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
print(D1.keys())

#Output
dict_keys(['India', 'China', 'Bhutan'])
MethodSyntaxDescription
get()dictionary.get(key, value)Returns the value for a key in the dictionary.
items()dictionary.items()Returns a list of (key, value) pairs.
keys()dictionary.keys()Returns a list of keys.
values()dictionary.values()Returns a list of values.

METHODS FOR ADDING NEW ELEMENT

Dictionaries in Python are mutable. We can add new items or change the value of existing elements in the dictionary using either square brackets or the update() method. If the key already exists, the existing value is updated, otherwise a new key: value pair is added to the dictionary.

1.Using [ ] brackets: Using the assignment operator we can add a new element to the dictionary as shown below.

Example: 

D1 = {"India": 91, "China": 86, "Bhutan": 975}
D1['Bhutan'] = 270
print("After updating, Bhutan: ",D1['Bhutan'])

#Output
After updating, Bhutan: 270

2. update(): This method is used to add a new element to the dictionary. The specified items can be a dictionary or an iterable object with key-value pairs. If the element is already present in the dictionary, its value gets updated with the given value.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
D1.update({"Denmark": 75})
print("Dictionary after update() method:",D1)

#Output
Dictionary after update() method: {'India': 91, 'China': 86, 'Bhutan': 975, 'Denmark': 75}

MethodSyntaxDescription
update()dictionary.update(iterable)Adds key: value pairs to the dictionary.

METHODS FOR DELETING CONTENTS

The following are some methods to delete contents from the dictionary.

  1. del(): The del() method deletes the entire dictionary. It is also used to remove the item with the specified key name.

Example: 

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
del(D1)
print(D1)

#Output
NameError: name 'D1' is not defined

2. clear(): The clear() method deletes all the items of the dictionary at once, resulting in an empty dictionary.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
D1.clear()
print("Output of clear() method:",D1)

#Output
Output of clear() method: {}

3. pop(): Using the pop() method, we can remove a specific item from a dictionary. This method deletes an item with the specified key and returns its value. 

It takes two parameters:

  • Key
  • Value(optional)

The key name of the item you want to remove is required. If the specified key is not found, then the default value will be returned.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
Popped_item = D1.pop("China")
print("The value corresponding to the popped item:",Popped_item)

#Output
The value corresponding to the popped item: 86

4. popitem(): The popitem() removes the last inserted item pair from the dictionary and returns. Before Python 3.7, popitem() removed any random pair from the dictionary.

It returns the removed pair as a tuple.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
D1.popitem()
print("Output of popitem() method:",D1)#Last item was deleted

#Output
Output of popitem() method: {'India': 91, 'China': 86}
MethodSyntaxDescription
del()del dictionaryDeletes the complete dictionary.
del dictionary[‘keyname’]Deletes the key value pair of the specified key name
clear()dictionary.clear()Removes all items from the dictionary.
pop()dictionary.pop(keyname,defaultvalue)Removes the key in the dictionary and returns its value.
popitem()dictionary.popitem()Removes and returns an arbitrary key: value pair from the dictionary.

METHODS TO CREATE AND COPY

  1. copy(): This method returns a shallow copy of the dictionary and doesn’t modify the original dictionary.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
D2 = D1.copy()
print("Output of copy() method:",D2)

#Output
Output of copy() method: {'India': 91, 'China': 86, 'Bhutan': 975}

2. fromkeys(): The fromkeys() method returns a dictionary containing the specified keys and values.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
D2 = D1.fromkeys(D1)
print("Output of fromkeys() method:",D2)

#Output
Output of fromkeys() method: {'India': dict_values([91, 86, 975]), 'China': dict_values([91, 86, 975]), 'Bhutan': dict_values([91, 86, 975])}
MethodSyntaxDescription
copy()dictionary.copy()Returns a copy of the specified dictionary.
fromkeys()dictionary.fromkeys(keys, value)Creates a new dictionary from the given iterable (string, list, set, tuple) as keys and with the specified value.

MISCELLANEOUS METHODS

Some of the remaining methods are given below:

  1. str(): This method is used to convert the dictionary into a printable string representation.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
D2 = str(D1)
print(D2)   #D2 is of type string

#Output
{'India': 91, 'China': 86, 'Bhutan': 975}

2. setdefault(): This method is used to return the value of the specified key in the dictionary. If the key is not found, then it adds the key with the specified default value. If the default value is not specified, then it sets a None value.

Example:

D1 = {"India": 91, "China": 86, "Bhutan": 975} 
D2 = {"India": 91, "China": 86, "Bhutan": 975}
D3 = {"India": 91, "China": 86, "Bhutan": 975, "Denmark": 75}
x = D1.setdefault("Denmark", 75)   #when the key doesn't exist
print("Value of x:",x)
y = D1.setdefault("India", 909)   #when the key exist
print("Value of y:",y)


#Output
Value of x: 75
Value of y: 91
MethodSyntaxDescription
str()str(dictionary)It converts the dictionary into a printable string representation.
setdefault()dictionary.setdefault(keyname, value)Returns the value of the specified key in the dictionary. 

Key Points

  1. Like other software, programming languages such as Python are regularly evolving to fix bugs and provide new features to the language. With every new release, some of the features become obsolete and are eventually phased out.

Similarly, when new versions were released, they introduced new methods, and some methods became deprecated.

  • Previously, the method cmp() was used to compare two dictionaries. However, it is no longer used.
  • The has_key() method was used to determine whether or not a key exists in the dictionary. To check it now, the operator ‘in’ is used.

Example of “in” Operator

D = {"India": 91, "China": 86, "Bhutan": 975}
print ("India" in D)

#Output
True

2. Python dictionary is internally implemented using a hashmap. That’s why operations like insertion, deletion and searching in a dictionary are much faster than any other python data structure like a list. 

The table below summarizes the complexity of the dictionary operations.

OperationInstructionTime complexity
copy()CopyO(n)
get()ObtainO(1)
update()ModifyO(1)
delete()DeleteO(1)
search()Dictionary Search(lookup)O(1)
iteration()Dictionary IterationO(n)

Frequently Asked Questions

How do you create a dictionary in python?

There are two basic ways to create a dictionary in python.
Using curly braces {}.
Using dict() constructor.

What is a dictionary in Python? Explain with an example.

A dictionary is a composite data type having a key and value pair.
Example: D1 = {“India”: 91, “China”: 86, “Bhutan”: 975}
Keys: India, China, Bhutan
Values: 91, 86, 975

How do you access a dictionary key in Python?

The keys() method is used to access keys of a dictionary.

Are Dictionaries ordered in Python?

From Python 3.6 onwards, the dictionary maintains insertion order by default.

What is a null statement in Python?

Python uses the keyword None to define null objects and variables. None is the value a function returns when there is no return statement in the function.

Key Takeaways

We’ve covered various python dictionary methods for accessing, deleting, updating, and copying content in this article. Dictionary is the most important and frequently used data structure. It is fast, mutable, dynamic, and can be nested, i.e. a dictionary can contain another dictionary.

Solving coding problems can help you improve your problem-solving skills. To grasp the intricacies of Python, we suggest you practice a few problems from CodeStudio.

It provides you hassle-free, adaptive, and excelling online courses, practice questions, blogs and mentor support.

By Vaishnavi Pandey

Exit mobile version