Python Programming

Python Dictionary methods and dict() Function

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.


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

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,

 >>> fish = {"g": "goldfish", "s":"shark", "n": "needlefish", "b":"barramundi",
"m":"mackerel"}
>>> fish
{'g': 'goldfish', 's': 'shark', 'n': 'needlefish', 'b': 'barramundi', 'm': 'mackerel'} 

 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,

 >>> mixed_dict = {"portable":"laptop", 9:11, 7:"julius"}
 >>> mixed_dict
{'portable': 'laptop', 9: 11, 7: 'julius'}
 >>> type(mixed_dict)
<class 'dict'>

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,

 >>> empty_dictionary = {}
 >>> empty_dictionary
{}
>>> type(empty_dictionary)
<class 'dict'>
An empty dictionary can be created as shown in and empty_dictionary is of dict type. In dictionaries, the order of key:value pairs does not matter. For example,
 >>> pizza = {"pepperoni":3, "calzone":5, "margherita":4}
 >>> fav_pizza = {"margherita":4, "pepperoni":3, "calzone":5}
 >>> pizza == fav_pizza
True

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,

>>> renaissance = {"giotto":1305, "donatello":1440, "michelangelo":1511,
"botticelli":1480, "clouet":1520}
 >>> renaissance["giotto"] = 1310
>>> renaissance
{'giotto': 1310, 'donatello': 1440, 'michelangelo': 1511, 'botticelli': 1480, 'clouet': 1520}
>>> renaissance["michelangelo"]
1511
>>> renaissance["leonardo"] = 1503
>>> renaissance
{'giotto': 1310, 'donatello': 1440, 'michelangelo': 1511, 'botticelli': 1480, 'clouet': 1520,
'leonardo': 1503}
>>> renaissance["piero"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'piero'

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,

>>> clothes = {"rainy":"raincoats", "summer":"tees", "winter":"sweaters"}
 >>> "spring" in clothes
False
>>> "spring" not in clothes
True

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,

 >>> numbers = dict(one=1, two=2, three=3)
>>> numbers
{'one': 1, 'two': 2, 'three': 3}

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

 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

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,

>>> presidents = {"washington":1732, "jefferson":1751, "lincoln":1809,
"roosevelt":1858, "eisenhower":1890}
>>> len(presidents)
5
>>> all_dict_func = {0:True, 2:False}
 >>> all(all_dict_func)
False
 >>> all_dict_func = {1:True, 2:False}
 >>> all(all_dict_func)
True
 >>> any_dict_func = {1:True, 2:False}
 >>> any(any_dict_func)
True
>>> sorted(presidents)
['eisenhower', 'jefferson', 'lincoln', 'roosevelt', 'washington']
 >>> sorted(presidents, reverse = True)
['washington', 'roosevelt', 'lincoln', 'jefferson', 'eisenhower']
 >>> sorted(presidents.values())
[1732, 1751, 1809, 1858, 1890]
 >>> sorted(presidents.items())
[('eisenhower', 1890), ('jefferson', 1751), ('lincoln', 1809), ('roosevelt', 1858),
('washington', 1732)]

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().

>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__
init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop',
'popitem', 'setdefault', 'update', 'values']

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,

>>> box_office_billion = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":
2011, "avengers":2012}
>>> box_office_billion_fromkeys = box_office_billion.fromkeys(box_office_billion)
>>> box_office_billion_fromkeys
{'avatar': None, 'titanic': None, 'starwars': None, 'harrypotter': None, 'avengers': None}
 >>> box_office_billion_fromkeys = box_office_billion.fromkeys(box_office_
billion, "billion_dollar")
 >>> box_office_billion_fromkeys
{'avatar': 'billion_dollar', 'titanic': 'billion_dollar', 'starwars': 'billion_dollar', 'harrypotter':
'billion_dollar', 'avengers': 'billion_dollar'}
6. >>> print(box_office_billion.get("frozen"))
None
7. >>> box_office_billion.get("frozen",2013)
2013
8. >>> box_office_billion.keys()
dict_keys(['avatar', 'titanic', 'starwars', 'harrypotter', 'avengers'])
9. >>> box_office_billion.values()
dict_values([2009, 1997, 2015, 2011, 2012])
10. >>> box_office_billion.items()
dict_items([('avatar', 2009), ('titanic', 1997), ('starwars', 2015), ('harrypotter', 2011),
('avengers', 2012)])
11. >>> box_office_billion.update({"frozen":2013})
12. >>> box_office_billion
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012, ' frozen': 2013}
13. >>> box_office_billion.setdefault("minions")
14. >>> box_office_billion
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012,
' frozen': 2013, 'minions': None}
 >>> box_office_billion.setdefault("ironman", 2013)
>>> box_office_billion
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012,
'minions': None, 'ironman': 2013}

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.

>>> box_office_billion.pop("avatar")
2009
 >>> box_office_billion.popitem()
('ironman', 2013)
 >>> box_office_billion.clear()
{}

 

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,

>>> list(box_office_billion.keys())
['avatar', 'titanic', 'starwars', 'harrypotter', 'avengers']
 >>> list(box_office_billion.values())
[2009, 1997, 2015, 2011, 2012]
 >>> list(box_office_billion.items())
[('avatar', 2009), ('titanic', 1997), ('starwars', 2015), ('harrypotter', 2011), ('avengers',
2012)]

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,

>>> countries = {}
>>> countries.update({"Asia":"Pakistan"})
>>> countries.update({"Europe":"Germany"})
>>> countries.update({"Africa":"Sudan"})
 >>> countries
{'Asia': Pakistan, 'Europe': 'Germany', 'Africa': 'Sudan'}

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]

>>> animals = {"r":"raccoon", "c":"cougar", "m":"moose"}
 >>> animals
{'r': 'raccoon', 'c': 'cougar', 'm': 'moose'}
 >>> del animals["c"]
 >>> animals
{'r': 'raccoon', 'm': 'moose'}

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



Examples:

Program to Demonstrate Nested Dictionaries

student_details = {"name": "Shahzada fawad", "registration_number": "UNU002", "sub_marks": {"python": 95, "java": 90, ".net": 85}}
def nested_dictionary():
                   
    print(f"Student Name {student_details['name']}")
    print(f"Registration Number {student_details['registration_number']}")
    average = sum(student_details["sub_marks"].values()) / len(student_details["sub_marks"])
    print(f"Average of all the subjects is {average}")
def main():
                   
                   
    nested_dictionary()
if __name__ == "__main__":
                   
    main()

Output:

Student Name Shahzada fawad
Registration Number UNU002
Average of all the subjects is 90.0


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

def main():
    
    sentence = input("Enter a sentence ")
    construct_dictionary = {"digits": 0, "lowercase": 0, "uppercase": 0}
    for each_character in sentence:
        
        if each_character.isdigit():
            
            
            construct_dictionary["digits"] += 1
        elif each_character.isupper():
            
        
            construct_dictionary["uppercase"] += 1
        elif each_character.islower():
            
            construct_dictionary["lowercase"] += 1
            print("The number of digits, lowercase and uppercase letters are")
        print(construct_dictionary)
if __name__ == "__main__":
    
    main()

Output:

Enter a sentence Shahzada Fawad From Programming digest 0333
The number of digits, lowercase and uppercase letters are
{'digits': 4, 'lowercase': 30, 'uppercase': 4} 

 

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:

def construct_character_dict(word):
    
    character_count_dict = dict()
    for each_character in word:
        
        character_count_dict[each_character] = character_count_dict.get(each_character, 0) + 1
        sorted_list_keys = sorted(character_count_dict.keys())
        for each_key in sorted_list_keys:
            print(each_key, character_count_dict.get(each_key))
def main():
    

    word = input("Enter a string ")
    construct_character_dict(word)
if __name__ == "__main__":
    
    main()

Output:

Enter a string programmingdigest
a 1
d 1
e 1
g 3
i 2
m 2
n 1
o 1
p 1
r 2
s 1
t 1

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

def main():
    
    count_words = dict()
    sentence = input("Enter a sentence ")
    words = sentence.split()
    for each_word in words:
        
    
        count_words[each_word] = count_words.get(each_word, 0) + 1
        print("The number of times each word appears in a sentence is")
        print(count_words)
if __name__ == "__main__":
    
    main()

OutPut:

Enter a sentence: Programming digest
The number of times each word appears in a sentence is
{'Programming': 1, 'digest': 1}

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.

 

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

Your email address will not be published. Required fields are marked *

Back to top button