Last modified on 2 October 2014, at 01:10

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, while lists, dictionaries, and sets other than frozensets are not. Dictionaries were available as early as in Python 1.4.

OverviewEdit

Dictionaries in Python at a glance:

dict1 = {}                     # Create an empty dictionary
dict2 = dict()                 # Create an empty dictionary 2
dict2 = {"r": 34, "i": 56}     # Initialize to non-empty value
dict3 = dict([("r", 34), ("i", 56)]) # Init from a list of tuples
dict4 = dict(r=34, i=56)       # Initialize to non-empty value 3
dict1["temperature"] = 32      # Assign value to a key
if "temperature" in dict1:     # Membership test of a key AKA key exists
  del dict1["temperature"]     # Delete AKA remove
equalbyvalue = dict2 == dict3
itemcount2 = len(dict2)        # Length AKA size AKA item count
isempty2 = len(dict2) == 0     # Emptiness test
for key in dict2:              # Iterate via keys
  print key, dict2[key]        # Print key and the associated value
  dict2[key] += 10             # Modify-access to the key-value pair
for value in dict2.values():   # Iterate via values
  print value
dict5 = {} # {x: dict2[x] + 1 for x in dict2 } # Dictionary comprehension in Python 2.7 or later
dict6 = dict2.copy()             # A shallow copy
dict6.update({"i": 60, "j": 30}) # Add or overwrite
dict7 = dict2.copy()
dict7.clear()                  # Clear AKA empty AKA erase
print dict1, dict2, dict3, dict4, dict5, dict6, dict7, equalbyvalue, itemcount2

Dictionary notationEdit

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 DictionariesEdit

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' in d
True
>>> 'dog' in d
False

Combining two DictionariesEdit

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 dictionaryEdit

del dictionaryName[membername]

ExercisesEdit

Write a program that:

  1. 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.
  2. Replaces the entry whose key is the integer 3, with the value "Pie".
  3. Asks the user for a string of digits, then prints out the values corresponding to those digits.

External linksEdit