We see here that Python shows a different ordering than how D was set up

# We see here that python shows a different ordering

This preview shows page 13 - 25 out of 47 pages.

We see here that Python “shows” a different ordering than how D was set up. Dictionaries are Different From Lists >>> D = {'I': 1, 'X': 10, 'V': 5} >>> D['X'] 10 >>> L = [1,5,10] >>> L 5 Dictionary values are accessed by key not subscript. Dictionary List Dictionaries are Different From Lists >>> D = {'I': 1, ‘V': 5, ‘X': 10} >>> D Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 2 Dictionary values are accessed by key not subscript. Python is complaining because 2 is not a key in the D Lists and Dictionaries 0 ---> 3 1 ---> 5 2 ---> 1 x ---> >>> x = [] >>> x.append(3) >>> x.append(5) >>> x.append(1) ‘I’ ---> 1 ‘V’ ---> 5 ‘X’ ---> 10 D ---> >>> D = {} >>> D[‘I’] = 1 >>> D[‘V’] = 5 >>> D[‘X’] = 10 Lists involve mappings from ints to values Dictionaries involve mappings from keys to values Lists and Dictionaries 0 ---> 3 1 ---> 5 2 ---> 1 x ---> >>> x = [] >>> x.append(3) >>> x.append(5) >>> x.append(1) ‘I’ ---> 1 ‘V’ ---> 5 ‘X’ ---> 10 D ---> >>> D = {} >>> D[‘I’] = 1 >>> D[‘V’] = 5 >>> D[‘X’] = 10 You “add” to a list using the append method. You add an item to a dictionary using a “new” key. Lists and Dictionaries 0 ---> 3 1 ---> 5 2 ---> 1 x ---> >>> L = [] >>> L.append(3) >>> L.append(5) >>> L.append(1) ‘I’ ---> 1 ‘V’ ---> 5 ‘X’ ---> 10 D ---> >>> D = {} >>> D[‘I’] = 1 >>> D[‘V’] = 5 >>> D[‘X’] = 10 Empty List Empty Dict L = [ ] and L = list() are equivalent D = { } and D = dict() are equivalent Dictionaries & Lists Access via the Square Bracket Notation: D[‘x’] L The len function can be applied to both: >>> x = [10,20,30] >>> len(x) 3 >>> D = {'a':10,'b':20,'c':30} >>> len(D) 3 Dictionaries & Lists Are Objects You can have multiple references to the same object. This is the idea of an alias. >>> x = [10,20,30] >>> y = x >>> x=100 >>> y [100, 20, 30] >>> D = {'a':10,'b':20,'c':30} >>> E = D >>> D['a'] = 100 >>> E {'a': 100, 'c': 30, 'b': 20} Dictionaries & Lists Are Objects It is possible to make copies. >>> x = [10,20,30] >>> y = list(x) >>> x = 100 >>> y [10, 20, 30] >>> D = {'a':10,'b':20,'c':30} >>> E = dict(D) >>> D['a']=100 >>> E {'a': 10, 'c': 30, 'b': 20} For-Loops and Dictionaries D = {‘I’:1,’V’:5,’X’:10,’L’:50} for d in D: print d, D[d] I 1 X 10 L 50 V 5 Again, dictionaries are not ordered. So extra steps would need to be taken here for things to be printed in a certain order. For-Loops and Dictionaries D = {‘I’:1,’V’:5,’X’:10,’L’:50} KeysOfD = D.keys() KeysOfD.sort() for d in KeysOfD: print d, D[d] I 1 L 50 V 5 X 10 Pretty Printing a Short Dictionary >>> D = {'I':1,'V':5,'X':10,'L':50} >>> str(D)  #### You've reached the end of your free preview.

Want to read all 47 pages?

• Fall '19
• Bracket, del d
• • • 