Python Dictionaries
Chapter 5
What is a Collection?
• A collection is nice because we can put more than one value in it
and carry them all around in one convenient package
• We have a bunch of values in a single “variable”
• We do this by having more than one place “in” the variable
• We have ways of finding the different places in the variable
A Story of Two Collections..
• List
A linear collection of values
Lookup by position 0 .. length-1
• Dictionary
A linear collection of key-value pairs
Lookup by "tag" or "key"
https://en.wikipedia.org/wiki/Index_card#/media/File:LA2-katalogkort.jpg
https://commons.wikimedia.org/wiki/File:Shelves-of-file-folders.jpg
Dictionaries
• Dictionaries are Python’s most powerful data collection
• Dictionaries allow us to do fast database-like operations in Python
• Similar concepts in different programming languages
- Associative Arrays - Perl / PHP
- Properties or Map or HashMap - Java
- Property Bag - C# / .Net
Dictionaries over time in Python
• Prior to Python 3.7 dictionaries did not keep entries in the
order of insertion
• Python 3.7 (2018) and later dictionaries keep entries in
the order they were inserted
• "insertion order" is not "always sorted order"
Below the Abstraction
• Python lists, dictionaries, and tuples are "abstract objects" designed
to be easy to use
• For now we will just understand them and use them and thank the
creators of Python for making them easy for us
• Using Python collections is easy. Creating the code to support them
is tricky and uses Computer Science concepts like dynamic memory,
arrays, linked lists, hash maps and trees.
• But that implementation detail is for a later course…
Lists (Review)
>>> cards = list()
>>> cards.append(12)
• We append values to the >>> cards.append(3)
>>> cards.append(75)
end of a List and look them >>> print(cards)
up by position [12, 3, 75]
>>> print(cards[1])
3
• We insert values into a >>> cards[1] = cards[1] + 2
Dictionary using a key and >>> print(cards)
[12, 5, 75]
retrieve them using a key
Dictionaries
>>> cabinet = dict()
>>> cabinet['summer'] = 12
• We append values to the >>> cabinet['fall'] = 3
>>> cabinet['spring'] = 75
end of a List and look them >>> print(cabinet)
up by position {'summer': 12, fall': 3, spring': 75}
>>> print(cabinet['fall'])
3
• We insert values into a >>> cabinet['fall'] = cabinet['fall'] + 2
Dictionary using a key and >>> print(cabinet)
{'summer': 12, 'fall': 5, 'spring': 75}
retrieve them using a key
Comparing Lists and Dictionaries
Dictionaries are like lists except that they use keys instead of
positions to look up values
>>> lst = list() >>> ddd = dict()
>>> lst.append(21) >>> ddd['age'] = 21
>>> lst.append(183) >>> ddd['course'] = 182
>>> print(lst) >>> print(ddd)
[21, 183] {'age': 21, 'course': 182}
>>> lst[0] = 23 >>> ddd['age'] = 23
>>> print(lst) >>> print(ddd)
[23, 183] {'age': 23, 'course': 182}