Python Dictionary

Python gives another composite information type called a word reference, which is like a rundown in that it is an assortment of articles.

This is what you’ll realize in this instructional exercise: You’ll cover the fundamental attributes of Python word references and figure out how to get to and oversee word reference information. Whenever you have completed this instructional exercise, you ought to have an excellent of when a word reference is the fitting information type to utilize, and how to do as such.

Characterizing a Dictionary

Word references are Python’s execution of an information structure that is all the more by and large known as a cooperative exhibit. A word reference comprises of an assortment of key-esteem sets. Each key-esteem pair maps the way in to its related worth.

You can characterize a word reference by encasing a comma-isolated rundown of key-esteem sets in wavy supports ({}). A colon (:) isolates each key from its related worth:

The accompanying characterizes a word reference that maps an area to the name of its relating Major League Baseball crew:

d = {
    <key>: <value>,
    <key>: <value>,
      .
      .
      .
    <key>: <value>
}

The following defines a dictionary that maps a location to the name of its corresponding Major League Baseball team:

>>>

>> MLB_team = {
... 'Colorado' : 'Rockies',
... 'Boston' : 'Red Sox',
... 'Minnesota': 'Twins',
... 'Milwaukee': 'Brewers',
... 'Seattle' : 'Mariners'
... }

Dictionary in Python is an unordered assortment of information esteems, used to store information esteems like a guide, which, dissimilar to different Data Types that hold just a solitary worth as a component, Dictionary holds key:value pair. Key-esteem is given in the word reference to make it more upgraded.

Note – Keys in a word reference don’t permit Polymorphism.

Consideration nerd! Reinforce your establishments with the Python Programming Foundation Course and gain proficiency with the essentials.

In the first place, your meeting arrangements Enhance your Data Structures ideas with the Python DS Course. Also in any case your Machine Learning Journey, join the Machine Learning – Basic Level Course

Making a Dictionary
In Python, a Dictionary can be made by putting an arrangement of components inside wavy {} supports, isolated by ‘comma’. Word reference holds sets of qualities, one being the Key and the other comparing pair component being its Key:value. Values in a word reference can be of any information type and can be copied, while keys can’t be rehashed and should be unchanging.

Note – Dictionary keys are case touchy, a similar name however various instances of Key will be dealt with unmistakably.

Adding components to a Dictionary

In Python Dictionary, the Addition of components should be possible in more than one way. Each worth in turn can be added to a Dictionary by characterizing esteem alongside the key for example Dict[Key] = ‘Worth’. Refreshing a current worth in a Dictionary should be possible by utilizing the inherent update() strategy. Settled key qualities can likewise be added to a current Dictionary.

Note-While adding a worth, assuming the key-esteem as of now exists, the worth gets refreshed in any case another Key with the worth is added to the Dictionary.

Getting to components from a Dictionary

To get to the things of a word reference allude to its key name. Key can be utilized inside square sections.

Getting to a component of a settled word reference

To get to the worth of any key in the settled word reference, use ordering [] language structure.

Eliminating Elements from Dictionary

Utilizing del catchphrase

In Python Dictionary, cancellation of keys should be possible by utilizing the del catchphrase. Utilizing the del catchphrase, explicit qualities from a word reference also as the entire word reference can be erased. Things in a Nested word reference can likewise be erased by utilizing the del catchphrase and giving a particular settled key and specific key to be erased from that settled Dictionary.

Note: The del Dict will delete the entire dictionary and hence printing it after deletion will raise an Error.

# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',
        'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},
        'B' : {1 : 'Geeks', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
# Deleting a Key from
# Nested Dictionary
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)

Output:

Initial Dictionary: 
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 6: 'To', 7: 'Geeks'}

Deleting a specific key: 
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}

Deleting a key from Nested Dictionary: 
{'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}

Using pop() method

Pop() method is used to return and delete the value of the key specified.

# Creating a Dictionary
Dict = {1: '', 'name': 'For', 3: 'Geeks'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(1)
print('\nDictionary after deletion: ' + str(Dict))
print('Value associated to poped key is: ' + str(pop_ele))

Output:

Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
Value associated to poped key is: Geeks

Using popitem() method

The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary.

# Creating Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting an arbitrary key
# using popitem() function
pop_ele = Dict.popitem()
print("\nDictionary after deletion: " + str(Dict))
print("The arbitrary pair returned is: " + str(pop_ele))

Output:

Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
The arbitrary pair returned is: (1, 'Geeks')

 Using clear() method

All the items from a dictionary can be deleted at once by using clear() method.

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting entire Dictionary
Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)

Output:

Deleting Entire Dictionary: 
{}

Dictionary Methods

Methods Description
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.

More Videos on Python Dictionary:
Python Dictionary Set 2
Python Dictionary Set 3

Dictionary Programs

  • Dictionary Methods – Set 1,Set 2
  • Get() method for dictionaries
  • Handling missing keys of dictionary
  • Ordered Dictionary
  • orderDict()
  • Chainmap
  • Majority Element
  • Dictionary and counter in Python to find winner of election
  • How to implement Dictionary with Python3
  • Possible Words using given characters in Python
  • Python dictionary, set and counter to check if frequencies can become same
  • Python dictionary intersection
  • OrderedDict() in Python
  • Check if binary representations of two numbers are anagram
  • Python Counter to find the size of largest subset of anagram words
  • Print anagrams together in Python using List and Dictionary
  • Convert a list of Tuples into Dictionary
  • Find all duplicate characters in string
  • Remove all duplicates words from a given sentence
  • Python Dictionary to find mirror characters in a string
  • Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
  • Second most repeated word in a sequence in Python
  • Python Dictionary Comprehension
  • K’th Non-repeating Character in Python using List Comprehension and OrderedDict
  • Scraping And Finding Ordered Words In A Dictionary using Python
  • Ways to sort list of dictionaries by values in Python – Using itemgetter
  • Merging two Dictionaries

Useful Links

  • Recent Articles on Python Dictionary
  • Output of Python programs – Dictionary
  • Output of Python programs – Dictionary
  • Coding Practice Platform
  • Multiple Choice Questions – Python
  • All articles in Python Category

Leave a Reply

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