Python - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Python Dictionary

Python Dictionary

shape Description

Dictionary reference is an unordered arrangement of key and esteem match. It is a holder that contains information, encased inside wavy props. The match i.e., key and esteem is known as thing. The key go in the thing must be one of a kind. The key and the esteem is isolated by a colon(:). This match is known as thing. Things are isolated from each other by a comma(,). Diverse things are encased inside a wavy support and this structures Dictionary. The following is an example. [c]data={1000:'sachin' ,1001:'nair' ,1002:'samuel'} print data [/c] Now compile the code result will be as follows. [c]>>> {1000:'sachin' ,1001:'nair' ,1002:'samuel'} >>> [/c]

Accessing Values To Dictionary

shape Description

To get to dictionary reference components, one can utilize the natural square sections alongside the way to acquire its esteem. The following is an example. [c]dict = {'Name': 'Sachin', 'Age': 37, 'Class': 'First'} print "dict['Name']: ", dict['Name'] print "dict['Age']: ", dict['Age'][/c] Now compile the code result will be as follows. [c]dict['Name']: Sachin dict['Age']: 37[/c]

Updating The Values In Dictionary

shape Description

The thing key-esteem match can be redesigned. Redesigning implies new thing can be included. The qualities can be adjusted. The following is an example. [c]dict = {'Name': 'Sachin', 'Age': 37, 'Class': 'First'} dict['Age'] = 38; # update existing entry dict['School'] = "DPS School"; # Add new entry print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School'][/c] Now compile the code result will be as follows. [c] dict['Age']: 38 dict['School']: DPS School [/c]

Deleting The Values In Dictionary

shape Description

Client can either evacuate singular word reference components or clear the whole substance of a lexicon. Client can likewise erase whole word reference in a solitary operation. The following is an example. [c]dict = {'Name': 'Sachin', 'Age': 37, 'Class': 'First'} del dict['Name']; # remove entry with key 'Name' dict.clear(); # remove all entries in dict del dict ; # delete entire dictionary print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School'][/c] Now compile the code result will be as follows. [c]dict['Age']: Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ", dict['Age']; TypeError: 'type' object is unsubscriptable[/c]

Summary

shape Key Points

  • The dict.remove is the method to vanish an elements from the dictionary.
  • The dict.values is the method to return the values from the dictionary.
  • The dict.items is the method to get the key and value pair from the dictioanry.