Python Programming/Dictionaries
A dictionary in Python is a collection of unordered values accessed by key rather than by index. The keys have to be hashable: integers, floating point numbers, strings, tuples, and, frozensets are hashable. Lists, dictionaries, and sets other than frozensets are not hashable. Dictionaries were available as early as in Python 1.4.
Overview
[edit | edit source]Dictionaries in Python at a glance:
dict1={}# Create an empty dictionarydict2=dict()# Create an empty dictionary 2dict2={"r":34,"i":56}# Initialize to non-empty valuedict3=dict([("r",34),("i",56)])# Init from a list of tuplesdict4=dict(r=34,i=56)# Initialize to non-empty value 3dict1["temperature"]=32# Assign value to a keyif"temperature"indict1:# Membership test of a key AKA key existsdeldict1["temperature"]# Delete AKA removeequalbyvalue=dict2==dict3itemcount2=len(dict2)# Length AKA size AKA item countisempty2=len(dict2)==0# Emptiness testforkeyindict2:# Iterate via keysprint(key,dict2[key])# Print key and the associated valuedict2[key]+=10# Modify-access to the key-value pairforkeyinsorted(dict2):# Iterate via keys in sorted order of the keysprint(key,dict2[key])# Print key and the associated valueforvalueindict2.values():# Iterate via valuesprint(value)forkey,valueindict2.items():# Iterate via pairsprint(key,value)dict5={}# {x: dict2[x] + 1 for x in dict2 } # Dictionary comprehension in Python 2.7 or laterdict6=dict2.copy()# A shallow copydict6.update({"i":60,"j":30})# Add or overwrite; a bit like list's extenddict7=dict2.copy()dict7.clear()# Clear AKA empty AKA erasesixty=dict6.pop("i")# Remove key i, returning its valueprint(dict1,dict2,dict3,dict4,dict5,dict6,dict7,equalbyvalue,itemcount2,sixty)
Dictionary notation
[edit | edit source]Dictionaries may be created directly or converted from sequences. Dictionaries are enclosed in curly braces, {}
>>>d={'city':'Paris','age':38,(102,1650,1601):'A matrix coordinate'}>>>seq=[('city','Paris'),('age',38),((102,1650,1601),'A matrix coordinate')]>>>d{'city':'Paris','age':38,(102,1650,1601):'A matrix coordinate'}>>>dict(seq){'city':'Paris','age':38,(102,1650,1601):'A matrix coordinate'}>>>d==dict(seq)True
Also, dictionaries can be easily created by zipping two sequences.
>>>seq1=('a','b','c','d')>>>seq2=[1,2,3,4]>>>d=dict(zip(seq1,seq2))>>>d{'a':1,'c':3,'b':2,'d':4}
Operations on Dictionaries
[edit | edit source]The operations on dictionaries are somewhat unique. Slicing is not supported, since the items have no intrinsic order.
>>>d={'a':1,'b':2,'cat':'Fluffers'}>>>d.keys()['a','b','cat']>>>d.values()[1,2,'Fluffers']>>>d['a']1>>>d['cat']='Mr. Whiskers'>>>d['cat']'Mr. Whiskers'>>>'cat'indTrue>>>'dog'indFalse
Combining two Dictionaries
[edit | edit source]You can combine two dictionaries by using the update method of the primary dictionary. Note that the update method will merge existing elements if they conflict.
>>>d={'apples':1,'oranges':3,'pears':2}>>>ud={'pears':4,'grapes':5,'lemons':6}>>>d.update(ud)>>>d{'grapes':5,'pears':4,'lemons':6,'apples':1,'oranges':3}>>>
Deleting from dictionary
[edit | edit source]deldictionaryName[membername]
Exercises
[edit | edit source]Write a program that:
- Asks the user for a string, then creates the following dictionary. The values are the letters in the string, with the corresponding key being the place in the string. https://docs.python.org/2/tutorial/datastructures.html#looping-techniques
- Replaces the entry whose key is the integer 3, with the value "Pie".
- Asks the user for a string of digits, then prints out the values corresponding to those digits.
External links
[edit | edit source]- 5.5. Dictionaries in Tutorial, docs.python.org
- 5.8. Mapping Types in Library Doc, docs.python.org