A Python dictionary is a un-ordered collection of Python objects (contrast with strings, lists, and tuples which are ordered sequences). What is new and particularly useful about dictionaries is that they can be indexed using any immutable object (unlike strings, lists and tuples that can only be indexed using integers). Because it is a collection (like strings, lists, and tuples) it shares characteristics such as iteration (for) and membership (in) as well as functions such as len(). Dictionaries are mutable (like lists).
Python dictionaries were unordered, but starting with Python 3.6 they are now ordered so you can sort them. They are insertion ordered. Dictionaries remember the order of items inserted. That is a recent change and is not reflected in the text -- not unusual when you try to keep up-to-date in this fast-moving field.
A Python set is like a mathematical set that you should be familiar with: an un-ordered collection of unique objects. Set operations are the expected ones from mathematics: union, intersection, etc. Because it is a collection it shares characteristics such as iteration (for) and membership (in) as well as functions such as len(). Sets are mutable.
Chapter 9: Dictionaries & Sets
A dictionary is a collection of pairs of Python objects: the pairs have the form key:value (note the colon ":"), the pairs are separated by commas and the collection is delimited by curly brackets. Any mixture of objects is allowed for a value; only an immutable can be a key.
Python sets are like mathematical sets: a collection of unique objects within curly braces.
Benford's Law (Wikipedia) refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the leading digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time.
How to build a dictionary to count items:
a_dict = {} # start with an empty dictionary for item in collection: if item not in a_dict: a_dict[item] = 1 # initialize else: # item is in a_dict a_dict[item] += 1 # incrementTo build a dictionary of lists: initialize to an empty list and append.
D = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4} # D is a dictionary with string keys L = sorted(D.items()) # L is a sorted list of tuples by the first element # L = [('Fourth', 4), ('first', 1), ('second', 2), ('third', 3)]This method will given us a list of tuples sorted in ascending order by the first element. Using this newly built list, one can create a sorted dictionary by calling the dict() method with L as its argument:
D_sorted = dict(L) # D is a dictionary with sorted keys in ascending order # D_sorted = {'Fourth': 4, 'first': 1, 'second': 2, 'third': 3}