October+12th+2016+by+Matt+An

Lesson Log on Oct.12th Dictionary Today we discussed about the dictionary, a new data type. First let's review the data type we had learned already:float, int, string, tuple, list and boolean. string and tuple are immutable, list is mutable. and dictionary, is a very flexible data type. it's index can be any type of data, like string. The basic form of the dictionary is { index:value}. we can consider it as a more flexible list, so we can use the method we used to get value from list in the dictionary type. we can create a dictionary first: code format="python" inventory={"apples":430,"peers":240,"peach":100} print(inventory) code

now we create a dictionary to show the inventory. we can delete the elements in the dictionary: code format="python" inventory={"apples":430,"peers":240,"peach":100} print(inventory) del inventory["peers"] print(inventory) code

we can modify the value in the dictionary: code format="python" inventory={"apples":430,"peers":240,"peach":100} inventory["peers"]-=100 print(inventory) code

and there is some useful functions in the dictionary class. for example: we can show all the index in the dictionary: code format="python" inventory.keys code

we can put index and values in a tuple and range them in a list: code format="python" inventory.items code we can show the value for all the index too:

code format="python" inventory.values code

Dictionary is too flexible,we can change it anytime so we need to ensure we didn't change the original dictionary. code format="python" opposites={"up":"down","right":"wrong","yes":"no"} alias=opposites alias["right"]="left" print(alias) print(opposites) copy=opposites.copy copy["right"]="privil" print(copy) print(opposites) code

alias point directly to the RAM address we save dictionary "opposites". so we can't change it directly, it will change the original value. so if we want change it, we need to copy it and then modify it.

with dictionary, we can make the program we already have work even better. Like the program for Fibonacci's sequence. the dictionary can help us run it faster: code format="python" def fib(n): if n<=1: return n   t=fib(n-1)+fib(n-2) return t print(fib(30)) alreadyknown={0:0,1:1} def fib(n): if n not in alreadyknown: new=fib(n-1)+fib(n-2) alreadyknown[n]=new return alreadyknown[n] print(fib(997)) code That's some basic use of dictionary.