Functions and Methods for Dictionaries (2024)


Next: Input and Output Up: Lists, Tuples and Dictionaries Previous: Dictionaries &nbsp Contents As is the case for strings and lists, the len function returns the number ofelements in a dictionary, that is, the number of key/value pairs. In addition, anumber of methods for dictionaries are available.

Since refering to a non-existent key in a dictionary raises a KeyErrorexception, you should avoid indexing a dictionary unless you're sure of the existenceof an entry with the key you are using. One alternative is to use a try/exceptclause (Section1.4.5) to trap the KeyError. Two methods are also usefulin this situation. The has_key method returns 1 (true) if the specified dictionary has the key which the method accepts as an argument, and 0 (false) otherwise. Thus,an if clause (Section6.4) can be used to take action if a specifiedkey does not exists. The get method also accepts a key as an argument, but it returns the value stored in the dictionary under that key if it exists, or an optionalsecond argument if there is no value for the key provided. With only one argument, get returns the value None when there is no value corresponding tothe key provided.

As an illustration of these methods, suppose we are counting how many times a wordappears in a file by using each word as a key to a dictionary called counts,and storing the number of times theword appears as the corresponding value. The logic behind the program would be to add one to the value if it already exists, or to set the value to one if it does not,since that will represent the first time the word is encountered. Here are threecode fragments illustrating the different ways of handling a value stored in wordwhich may or may not already be a key in the dictionary. (Remember that counts would have to be initialized toan empty dictionary before any elements could be added to it.)

# method 1: exceptions try: counts[word] = counts[word] + 1 except KeyError: counts[word] = 1 # method 2: check with has_key if counts.has_key(word): counts[word] = counts[word] + 1 else: counts[word] = 1 # method 3: use get counts[word] = counts.get(word,0) + 1
Although the third method is the shortest, it may not be obvious why it works. When an entry with the specified key already exists, the get methodwill return that entry and increment it by 1. If the key does not exist, the optionalsecond argument to get forces it to return a value of 0, which, when incremented by 1 gives the correct initial value.

As of version 2.2, it is possible to iterate over a dictionary using a forloop; the operation willreturn the keys of the dictionary in an arbitrary order. In addition, the inoperator can be used as an alternative to the has_key method to determine if a particular key is present in a dictionary.

A few other methods provide alternative ways of accessing the keys, values or key/valuepairs of a dictionary. The keys method returns a list of just the keys of a dictionary, and the values method returns a list of just the values. Whilethe returned lists have their elements stored in an arbitrary order, correspondingelements in the two lists will be key/value pairs. The items methodreturns a list of tuples consisting of all the key/value pairs. Returning to the example using names as keys and phone numbers as values, here are the results of invoking these three methods on the phonedict dictionary:

>>> phonedict = {'Fred':'555-1231','Andy':'555-1195','Sue':'555-2193'} >>> phonedict.keys()['Fred', 'Sue', 'Andy']>>> phonedict.values()['555-1231', '555-2193', '555-1195']>>> phonedict.items()[('Fred', '555-1231'), ('Sue', '555-2193'), ('Andy', '555-1195')]

To remove all the elements of a dictionary, use the clear method. This differsfrom using the del operator on the dictionary in that the dictionary, althoughempty, still exists. To make a copy of a dictionary, use the copy method; remember that assignment of a dictionary to another variable may not do what youthink (Section6.1).

Python provides the update method to allow your to merge all the key/value pairs in one dictionary with those in another. If the original dictionary has an entrywith the same key as one in the dictionary used for updating, the value from the dictionary used for updating will be placed in the original dictionary.

>>> master = {'orange':3,'banana':5,'grapefruit':2}>>> slave = {'apple':7,'grapefruit':4,'nectarine':3}>>> master.update(slave)>>> master{'banana': 5, 'orange': 3, 'nectarine': 3, 'apple': 7, 'grapefruit': 4}
Since both master and slave had entries for the key ``grapefruit'', the value found in master after the callto update is the one which was in slave.
Next: Input and Output Up: Lists, Tuples and Dictionaries Previous: Dictionaries &nbsp Contents
Phil Spector2003-11-12
Functions and Methods for Dictionaries (2024)
Top Articles
Test-Taking Strategy
Configurar un buzón de correo en Gmail
13 Easy Ways to Get Level 99 in Every Skill on RuneScape (F2P)
Paris 2024: Kellie Harrington has 'no more mountains' as double Olympic champion retires
Mychart Mercy Lutherville
Hallowed Sepulchre Instances & More
Https Www E Access Att Com Myworklife
Mylife Cvs Login
Deshret's Spirit
OnTrigger Enter, Exit ...
Youtube Combe
Tokioof
Seafood Bucket Cajun Style Seafood Restaurant in South Salt Lake - Restaurant menu and reviews
Craigslist Alabama Montgomery
Christina Khalil Forum
Simplify: r^4+r^3-7r^2-r+6=0 Tiger Algebra Solver
Canvas Nthurston
111 Cubic Inch To Cc
Uky Linkblue Login
CANNABIS ONLINE DISPENSARY Promo Code — $100 Off 2024
Amazing deals for DKoldies on Goodshop!
Mychart Anmed Health Login
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
Military life insurance and survivor benefits | USAGov
Www.craigslist.com Austin Tx
Parkeren Emmen | Reserveren vanaf €9,25 per dag | Q-Park
Sessional Dates U Of T
10 Best Places to Go and Things to Know for a Trip to the Hickory M...
Craigslist Efficiency For Rent Hialeah
Sacramento Craigslist Cars And Trucks - By Owner
Unm Hsc Zoom
Autotrader Bmw X5
Laurin Funeral Home | Buried In Work
7543460065
Ashoke K Maitra. Adviser to CMD's. Received Lifetime Achievement Award in HRD on LinkedIn: #hr #hrd #coaching #mentoring #career #jobs #mba #mbafreshers #sales…
Qlima© Petroleumofen Elektronischer Laserofen SRE 9046 TC mit 4,7 KW CO2 Wächter • EUR 425,95
All Obituaries | Sneath Strilchuk Funeral Services | Funeral Home Roblin Dauphin Ste Rose McCreary MB
Craigslist Odessa Midland Texas
5A Division 1 Playoff Bracket
Santa Clara County prepares for possible ‘tripledemic,’ with mask mandates for health care settings next month
'The Night Agent' Star Luciane Buchanan's Dating Life Is a Mystery
Brown launches digital hub to expand community, career exploration for students, alumni
Searsport Maine Tide Chart
Paperlessemployee/Dollartree
VerTRIO Comfort MHR 1800 - 3 Standen Elektrische Kachel - Hoog Capaciteit Carbon... | bol
Air Sculpt Houston
Playboi Carti Heardle
Nfsd Web Portal
Unity Webgl Extreme Race
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 6341

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.