Python Reading Key and Value From a Dictionary

Python - Dictionary


Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without whatsoever items is written with merely two curly braces, similar this: {}.

Keys are unique within a dictionary while values may not be. The values of a dictionary can exist of any type, but the keys must exist of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary

To access dictionary elements, yous can use the familiar foursquare brackets along with the key to obtain its value. Following is a simple example −

#!/usr/bin/python  dict = {'Proper noun': 'Zara', 'Age': 7, 'Form': 'First'} print "dict['Name']: ", dict['Proper noun'] print "dict['Historic period']: ", dict['Historic period']        

When the above code is executed, information technology produces the following effect −

dict['Name']:  Zara dict['Historic period']:  7        

If nosotros endeavour to admission a information particular with a primal, which is not function of the dictionary, we get an error as follows −

#!/usr/bin/python  dict = {'Proper noun': 'Zara', 'Age': 7, 'Class': 'Offset'} print "dict['Alice']: ", dict['Alice']        

When the above code is executed, it produces the post-obit consequence −

dict['Alice']: Traceback (well-nigh recent call last):    File "test.py", line 4, in <module>       impress "dict['Alice']: ", dict['Alice']; KeyError: 'Alice'        

Updating Lexicon

Y'all can update a dictionary past adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry every bit shown below in the simple example −

#!/usr/bin/python  dict = {'Proper noun': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry  print "dict['Historic period']: ", dict['Age'] print "dict['Schoolhouse']: ", dict['School']        

When the above code is executed, information technology produces the following outcome −

dict['Age']:  eight dict['School']:  DPS School        

Delete Lexicon Elements

You can either remove individual dictionary elements or clear the entire contents of a dictionary. You tin can too delete entire lexicon in a single operation.

To explicitly remove an entire dictionary, just use the del argument. Following is a elementary case −

#!/usr/bin/python  dict = {'Name': 'Zara', 'Historic period': 7, 'Course': 'Offset'} del dict['Name']; # remove entry with key 'Name' dict.clear();     # remove all entries in dict del dict ;        # delete entire dictionary  impress "dict['Historic period']: ", dict['Age'] impress "dict['Schoolhouse']: ", dict['Schoolhouse']        

This produces the post-obit result. Annotation that an exception is raised considering after del dict lexicon does non exist any more than −

dict['Historic period']: Traceback (most recent call last):    File "examination.py", line viii, in <module>       print "dict['Historic period']: ", dict['Historic period']; TypeError: 'type' object is unsubscriptable        

Note − del() method is discussed in subsequent section.

Properties of Dictionary Keys

Lexicon values have no restrictions. They can exist whatsoever arbitrary Python object, either standard objects or user-defined objects. All the same, same is not truthful for the keys.

There are ii of import points to recall about dictionary keys −

(a) More than than 1 entry per key not allowed. Which means no indistinguishable primal is immune. When duplicate keys encountered during assignment, the final consignment wins. For instance −

#!/usr/bin/python  dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} impress "dict['Name']: ", dict['Name']        

When the above code is executed, it produces the following result −

dict['Proper name']:  Manni        

(b) Keys must exist immutable. Which ways you can utilise strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a uncomplicated example −

#!/usr/bin/python  dict = {['Name']: 'Zara', 'Age': 7} impress "dict['Proper noun']: ", dict['Name']        

When the higher up code is executed, information technology produces the following consequence −

Traceback (most recent call last):    File "test.py", line 3, in <module>       dict = {['Name']: 'Zara', 'Age': 7}; TypeError: unhashable type: 'list'        

Built-in Dictionary Functions & Methods

Python includes the following dictionary functions −

Sr.No. Role with Clarification
one cmp(dict1, dict2)

Compares elements of both dict.

two len(dict)

Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

3 str(dict)

Produces a printable string representation of a dictionary

iv blazon(variable)

Returns the type of the passed variable. If passed variable is lexicon, then it would return a dictionary blazon.

Python includes following dictionary methods −

Sr.No. Methods with Description
i dict.clear()

Removes all elements of dictionary dict

2 dict.copy()

Returns a shallow re-create of dictionary dict

3 dict.fromkeys()

Create a new dictionary with keys from seq and values set to value.

four dict.get(cardinal, default=None)

For cardinal key, returns value or default if fundamental not in dictionary

5 dict.has_key(key)

Returns true if fundamental in dictionary dict, false otherwise

6 dict.items()

Returns a list of dict's (key, value) tuple pairs

7 dict.keys()

Returns list of dictionary dict's keys

eight dict.setdefault(key, default=None)

Like to get(), just volition set up dict[key]=default if fundamental is not already in dict

9 dict.update(dict2)

Adds dictionary dict2's key-values pairs to dict

10 dict.values()

Returns list of dictionary dict'southward values

Useful Video Courses


Python Online Training

Video

Python Essentials Online Training

Video

Learn Python Programming in 100 Easy Steps

Video

Python with Data Science

Video

Python 3 from scratch to become a developer in demand

Video

Python Data Science basics with Numpy, Pandas and Matplotlib

Video

wisebusell.blogspot.com

Source: https://www.tutorialspoint.com/python/python_dictionary.htm

0 Response to "Python Reading Key and Value From a Dictionary"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel