Python Dictionary methods and dict() Function

(Last Updated On: May 19, 2020)

Description:

Python Dictionary-this is a very detailed tutorial about Dictionary in python in this you will also learn what is build-in functions of Dictionary.


Creating a Python Dictionary

A dictionary is a collection of an unordered set of key:value pairs, with the requirement that the keys are unique within a Python Dictionary. Dictionaries are constructed using curly braces { }, wherein you include a list of key:value pairs separated by commas. Also, there is a colon (:) separating each of these key and value pairs, where the words to the left of the colon operator are the keys and the words to the right of the colon operator are the values. disparate lists, which are indexed by a range of numbers, dictionaries are indexed by keys. Here a key along with its associated value is called a key:value pair. Python Dictionary keys are case sensitive.

The syntax for creating a Python Dictionary is,

dictionary_name = {key_1:value_1, key_2:value_2, key_3:value_3, ………,key_n:value_n}

Opening Curly

Braces Closing Curly

Braces Separated

by Comma

User defined

For example,

 Placing a comma-separated list of key:value pairs within the curly braces adds initial key:value pairs to the Python Dictionary. In This way the dictionaries are written on output. The keys in the Python Dictionary fish are “g”, “s”, “n”, “b”, and “m” and the values associated with these keys are “goldfish”, “shark”, “needlefish”, “barramundi”, and “mackerel”. Each of the keys and values here is of string type. A value in the Python Dictionary can be of any datatype including string, number, list, or Python Dictionary itself. Python Dictionary keys are immutable type and can be either a string or a number. Since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend(), you cannot use lists as keys. Duplicate keys are not allowed in the Python Dictionary. In dictionaries, the keys and their associated values can be of different types.



For example,

In the Python Dictionary, mixed_dict, keys and their associated values are all of different types. For numbers as keys in dictionaries, it need not start from zero and it can be of any number. You can determine the type of mixed_dict by passing the variable name as an argument to type() function. In Python, the dictionary type is called as dict. You can create an empty Python Dictionary by specifying a pair of curly braces and without any key:value pairs. The syntax is,

dictionary_name = { }

For example,

The dictionaries pizza and fav_pizza have the same key:value pairs but in a different order. If you compare these two dictionaries, it results in Boolean True value. This indicates that the ordering of key:value pairs does not matter in dictionaries. Slicing in dictionaries is not allowed since they are not ordered like lists. Prior to Python 3.6 version, the execution of Python Dictionary statements resulted in an unordered output of key:value pairs. However, starting from Python 3.6 version, the output of Python Dictionary statements is ordered key:value pairs. Here, ordered means “insertion ordered”, i.e., dictionaries remember the order in which the key:value pairs were inserted.


Accessing and Modifying key:value Pairs in Python Dictionary

Each individual key:value pair in a Python Dictionary can be accessed through keys by specifying it inside square brackets. The key provided within the square brackets indicates the key:value pair being accessed. The syntax for accessing the value for a key in the Python Dictionary is, dictionary_name[key] The syntax for modifying the value of an existing key or for adding a new key:value pair to a Python Dictionary is,

dictionary_name[key] = value

If the key is already present in the Python Dictionary, then the key gets updated with the new value. If the key is not present then the new key:value pair gets added to the dictionary.

For example,

Since dictionaries are capricious, you can add a new key:value pair or change the values for existing keys using the assignment operator. For the Python Dictionary renaissance, you can modify the existing values for the keys. The value for the key giotto is updated from 1305 to 1310 as shown in using the assignment operator. The value associated with the key michelangelo is displayed in. You can add a new key:value pair by specifying the name of the Python Dictionary followed by a bracket within where you specify the name of the key and assign a value to it. If you try to access a non-existing key then it results in KeyError. You can check for the presence of a key in the Python Dictionary using in and not in membership operators. It returns either a Boolean True or False value. For example,

In line 2 and 3, the presence of the key spring is checked in the Python Dictionary clothes


 dict() Function

The built-in dict() function is used to create a Python Dictionary. The syntax for dict() function when the optional keyword arguments used is,

dict([**kwarg])

The function dict() returns a new Python Dictionary initialized from an optional keyword argument and a possibly empty set of keyword arguments. If no keyword argument is given, an empty Python Dictionary is created. If keyword arguments are given, the keyword arguments and their values of the form kwarg = value are added to the Python Dictionary as key:value pairs.

For example,

Keyword arguments of the form kwarg = value are converted to key:value pairs for numbers dictionary. The syntax for dict() function when iterables used is,

dict(iterable[, **kwarg])

You can specify an iterable containing exactly two objects as tuple, the key and value in the dict() function. For example

The dict() function builds dictionaries directly from sequences of key, value tuple pairs.


Built-In Functions Used on Python Dictionary

There are many built-in functions for which a Python Dictionary can be passed as an argument The main operations on a dictionary are storing a value with some key and extracting the value for a given key.

For example,

You can find the number of key:value pairs in the Python Dictionary presidents  using the len() function. In Python, any non-zero integer value is True, and zero is interpreted as False. If all the keys are Boolean True values, then the output is True else it is False Boolean value for all() function in dictionaries. If any one of the keys is True then it results in a True Boolean value else False Boolean value for any() function in dictionaries. The sorted() function returns the sorted list of keys by default in ascending order without modifying the original key:value pairs. You can also get a list of keys sorted in descending order by passing the second argument as reverse=True. In the case of Python Dictionary keys being type strings, they are sorted based on their ASCII values. You can obtain a sorted list of values instead of keys by using the values() method along with the Python Dictionary name . A sorted list of key, value tuple pairs, which are sorted based on keys, are obtained by using the items() method along with the dictionary name.



Built-in Functions Description

len():

The len() function returns the number of items (key:value pairs) in a Python Dictionary.

all():

The all() function returns Boolean True value if all the keys in the Python Dictionary are True else returns False.

any():

The any() function returns Boolean True value if any of the key in the Python Dictionary is True else returns False.

sorted():

The sorted() function by default returns a list of items,which are sorted based on Python Dictionary keys.

Python Dictionary Methods

Python Dictionary allows you to store data in key:value format without depending on indexing. You can get a list of all the methods associated with dict  bypassing the dict function to dir().

Various methods associated with dict are displayed.

Python Dictionary

Various Python Dictionary Methods Dictionary and Syntax Description

clear():

The clear() method removes all the key:value pairs from the Python Dictionary.

fromkeys(seq[, value]):

The fromkeys() method creates a new Python Dictionary from the given sequel of elements with a value provided by the user.

get(key[, default]):

The get() method returns the value associated with the specified key in the Python Dictionary. If the key is not present then it returns the default value. If default is not given, it defaults to None, so that this approach never raises a KeyError.

items():

The items() method returns a new view of Python Dictionary’s key and value pairs as tuples.

keys():

The keys() method returns a new view consisting of all the keys in the Dictionary.

pop(key[, default]):

The pop() method removes the key from the Python Dictionary and returns its value. If the key is not present, then it returns the default value. If default is not given and the key is not in the Python Dictionary, then it results in KeyError.

popitem():

The popitem() method removes and returns an arbitrary (key, value) tuple pair from the Dictionary. If the dictionary is empty, then calling popitem() results in KeyError.

setdefault(key[, default]):

The setdefault() method returns a value for the key present in the Python Dictionary. If the key is not present, then insert the key into the dictionary with a default value and return the default value. If key is present, default defaults to None, so that this method never raises a KeyError.

update([other]):

The update() method updates the Dictionary with the key:value pairs from other dictionary object and it returns None.

values():

The values() method returns a new view consisting of all the values in the Python Dictionary.


For example,

The objects returned by dict.keys(), dict.values(), and dict.items() are view objects. They provide a dynamic view of the Python Dictionary’s entries, thus when the Dictionary changes, the view reflects these changes.

 

Various operations on dictionaries are carried out using  Dictionary methods.

The dict_keys, dict_values, and dict_items data types returned by various methods of Python Dictionary are read-only views and cannot be edited directly. If you want to convert dict_keys, dict_values, and dict_items data types returned from keys(), values(), and items() methods to a true list then pass their list, such as returned values, to list() function. Whenever there is a modification to the dictionary, it gets reflected in the views of these data types. For example,

The dict_keys, dict_values, and dict_items returned from keys(), values(), and items() are converted to true list using the list() function.


Populating Python Dictionary with key:value Pairs

One of the common ways of populating dictionaries is to start with an empty dictionary { }, then use the update() method to assign a value to the key using assignment operator. If the key does not exist, then the key:value pairs will be created automatically and added to the Python Dictionary.

For example,

Create an empty dictionary country and start populating key:value pairs to the countries Python Dictionary using the update() function and finally display the key:value pairs of the countries dictionary. Within the update() function the key:value pair should be enclosed within the curly braces. the Dictionary can also be built using dictionary_name[key] = value

syntax by adding key:value pairs to the dictionary.


Traversing of Python Dictionary

A for loop can be used to iterate over keys or values or key:value pairs in dictionaries. If you iterate over a Dictionary using a for loop, then, by default, you will iterate over the keys. If you want to iterate over the values, use values() method and for iterating over the key:value pairs, specify the Python Dictionary’s items() method explicitly. The dict_keys, dict_values, and dict_items data types returned by Python Dictionary methods can be used in for loops to iterate over the keys or values or key:value pairs.

del Statement

To delete the key:value pair, use the del statement followed by the name of the dictionary along with the key you want to delete.

del dict_name[key]

In the animals  dictionary, you can remove the key:value pair of“c”: “cougar”



Examples:

Program to Demonstrate Nested Dictionaries

Output:


Python Dictionary

The use of dictionaries within dictionaries is called nesting of dictionaries. You can assign a dictionary as a value to a key inside another dictionary. A dictionary is associated as a value to the sub_marks dictionary. Inside the nested_dictionary()  function, student name, registration number, and average marks are displayed. The value returned from student_details[sub_marks] is of dictionary type i.e.,

>>> student_details[“sub_marks”]

{‘python’: 95, ‘java’: 90, ‘.net’: 85}.

To access all the values of the dictionary associated with a sub_marks key in the student_details dictionary, you need to specify the name of student_details dictionary followed by sub_marks as the key and combine it with values() method using dot notation. Even though a single level of nesting dictionaries may prove useful, having multiple levels of nesting may make the code unreadable.


Write a Program That Accepts a Sentence and Calculate the Number of Digits, Uppercase and Lowercase Letters

Output:

 

Python Dictionary

In the main() function, the user enters a sentence that is stored in sentence variable. The construct_dictionary has three keys digits, lowercase and uppercase with each of them having zero as their initial value. Loop through each character in the sentence. If the character is a digit, then the value for digits key in construct_dictionary is incremented by one. If the character is in lowercase, then the value for lowercase key in construct_dictionary is

incremented by one. If the character is in uppercase, then the value for uppercase key in construct_dictionary is incremented by one. Finally, key:value pair in the construct_dictionary dictionary is displayed.


Write Python Program to Count the Number of Characters in a String Using Dictionaries. Display the Keys and Their Values in Alphabetical Order:

Output:

Python Dictionary
In the main() function, the user enters a string that is passed as argument to the construct_character_dict()  function. In the construct_character_dict() function, start by initializing character_count_dict to empty the dictionary. Loop through each character in the word string. If the character is not present as a key in the dictionary, then the get() method takes a default value of zero to which a value of one is added and is assigned to character_count_dict dictionary with the key being the iterating variable. If the character is already present as a key in the dictionary, then the value associated with the key is incremented by one and this latest value is associated with the key by overwriting the existing value. The keys are sorted in ascending order using the sorted() function, and the sorted list of key:value pairs are assigned to sorted_list_keys. The number of times a character appearing within the userentered word is displayed by looping through each key in the sorted_list_keys dictionary. The value for each key in the sorted_list_keys dictionary is displayed using get() method.



Write Python Program to Count the Number of Times Each Word Appears in a Sentence

OutPut:

Python Dictionary

In the main() function, you start by initializing count_words to empty dictionary. The user enters a sentence, which is split into a list of words using the split() function. Loop through each word in the words list. If the word is not present as a key in the dictionary, then the get() method takes a default value of zero to which a value of one is added and assigned to count_words dictionary with the key being the value of the iterating variable. If the word is already present as a key in the dictionary, then the value associated with the key is incremented by one and this latest value is associated with the key by overwriting the existing value.

 

Recommended For You

About the Author: Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply