A dictionary is like a list, but more general. In a list, the index positions have to be integers; in a dictionary, the indices can be (almost) any type.
>>> x = {} #This is False >>> print(x) {}
You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values.
>>> x['one'] = 'apple' >>> print(x) {'one': 'apple'}
In general, the order of items in a dictionary is unpredictable.
>>> x = {'one':'apple','two':'banana','three':'orange'} >>> print(x) {'one':'apple','three':'orange','two':'banana'} >>> print(x['two']) 'banana' >>> len(x) 3
Adding New Key-Value Pairs
>>> alien = {} >>> alien['color'] = 'green' >>> alien['point'] = 5 >>> print(alien) {'color': 'green', 'points': 5}
To create a dictionary, start with an empty one, and add the key-value pairs. The keys should be immutable and there is no repeated key. Lists cannot be keys in the dictionary.
Modifying Values in a Dictionary
>>> alien['color'] = 'yellow' >>> print(alien) {'color': 'yellow', 'points': 5}
Removing Key-Value Pairs
>>> del alien['points'] >>> print(alien) {'color': 'yellow'}
Merge two dictionaries
>>> dict1 = { "name":"owen", "age": 18 } >>> dict2 = { "birthday": "1999-11-22"} >>> x = dict1|dict2 >>> print(x) {'name': 'owen', 'age': 18, 'birthday': '1999-11-22'}
>>> a = { 'x' : 1 , 'y' : 2 } >>> b = { 'y' : 3 , 'z' : 4 } >>> c = a|b >>> print(c) {'x': 1, 'y': 3, 'z': 4}
The in operator works on dictionaries. (keys) To see whether something appears as a value in a dictionary, you can use the method .values().
>>> x = {'one': 'apple', 'two': 'banana', 'three': 'orange'} >>> 'one' in x True >>> 'uno' in x False >>>'orange' in x.values() True
>>> stuff = {} >>> dir(stuff)
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update','values']
>>> help(dict.get) Help on method_descriptor: get(self, key, default=None, /) Return the value for key if key is in the dictionary, else default.
>>> counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100} >>> print(counts.get('jan', 0)) #0 is the default value 100 >>> print(counts.get('anni', 1550)) 1550
word = 'banana' d = {} word_list = list('banana') for c in word_list: d[c] = d.get(c,0) + 1 print(d)
{'b': 1, 'a': 3, 'n': 2}
# Looping Through All Key-Value Pairs favorite = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', } for x, y in favorite.items(): print(x, y)
jen python
sarah c
edward ruby
# Looping Through All Values for y in favorite.values(): print(y)
python
c
ruby
# Looping Through All the Keys in a Dictionary for x in favorite.keys(): print(x)
jen
sarah
edward
You can nest a set of dictionaries inside a list, a list of items inside a dictionary, or even a dictionary inside another dictionary. A list or a dictionary cannot be the key (The key should be immutable).
Dictionaries in a list
alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'yellow', 'points': 10} alien_2 = {'color': 'red', 'points': 15} aliens = [alien_0, alien_1, alien_2]
A List in a Dictionary
pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese'], } print(pizza['crust'], pizza['toppings'][1])
thick extra cheese
A Dictionary in a Dictionary
users = { 'aeinstein': { 'first': 'albert', 'last': 'einstein', 'location': 'princeton', }, 'mcurie': { 'first': 'marie', 'last': 'curie', 'location': 'paris', }, }
full_name = users['aeinstein']['first']+" "+users['aeinstein']['last'] location = users['aeinstein']['location'] print("Full name: " + full_name) print("Location: " + location)
Full name: Albert Einstein
Location: Princeton
Elements are key-value pairs. Empty dictionary {}
Features:unpredictable order, key-value pairs are mutable (keys are immutable, but you can modify values). Do not make repeated keys.
.get() (value or default value)
Looping: .items(), .keys(), .values()
in operator works on keys (but you can use .values())
Nesting: A list of dictionaries, a list in a dictionary, a dictionary in a dictionary
print("简易记账本(九月)") Sept=[] for date in range(31): # Sept.append([]) Sept.append({})
while True: day=int(input("请问输入几号的开销?结束请输入0:")) if day==0: break else: print("请输入每一笔开销,结束请输入0:") n=1 while True: each = float(input("第"+str(n)+"笔:")) if each == 0: break else: # Sept[day-1].append(each) y = input("请选择: a.衣 b.食 c.住 d.行 e.其他") Sept[day-1][y]=Sept[day-1].get(y,0)+each n = n + 1 print("记录成功")
total=0 for each_day in Sept: if each_day: # total = total + sum(each_day) total = total + sum(each_day.values()) print("本月支出汇总报告") print("总支出:" + str(total))
sub = {} items = ['a', 'b', 'c', 'd', 'e'] for each_day in Sept: for z in items: sub[z] = each_day.get(z,0)+sub.get(z,0) print("衣:", sub['a']) print("食:", sub['b']) print("住:", sub['c']) print("行:", sub['d']) print("其他:", sub['e'])
A tuple is a sequence of values much like a list. The important difference is that tuples are immutable
The empty tuple can be written as tuple().
>>> t = () #Empty is False >>> print(t) () >>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you have to include the final comma:
>>> t1 = ('a',) >>> type(t1) tuple >>> t2 = ('a') >>> type(t2) str
Most list operators also work on tuples.
>>> t = ('a', 'b', 'c', 'd', 'e') >>> print(t[0]) 'a' >>> print(t[1:3]) ('b', 'c')
Tuple is immutable. You can't modify the elements of a tuple, but you can replace one tuple with another:
>>> t[0] = 'A' TypeError: object doesn't support item assignment >>> t = ('A',) + t[1:] >>> print(t) ('A', 'b', 'c', 'd', 'e')
If you want to modify a tuple, you can convert it to a list, and then convert it back.
>>> t = ('a', 'b', 'c', 'd', 'e') >>> s = list(t) >>> s[0] = 'A' >>> t = tuple(s)
Comparing and sorting (the same for lists)
>>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) True
>>> t = [(2, 4), (0, 1, 2), (0, 3, 4)] >>> t.sort() >>> print(t) [(0, 1, 2), (0, 3, 4), (2, 4)]
in operator (the same for lists)
>>> t = ('a', 'b', 'c', 'd', 'e') >>> print('a' in t) True
Multiple Assignment (the same for lists)
>>> m = ('have', 'fun') >>> x, y = m >>> x 'have' >>> y 'fun' >>> x, y = y, x #swap
Iteration with multiple values (the same for lists in lists, tuples in lists, lists in tuples)
t = [('a',1), ('b',2), ('c',3)] # t = (('a',1), ('b',2), ('c',3)) # t = [['a',1], ['b',2], ['c',3]] for x, y in t: print(x) print(y)
>>> d = {'a':10, 'b':1, 'c':22} >>> t = list(d.items()) >>> t [('b', 1), ('a', 10), ('c', 22)]
Using tuples as keys in dictionaries
>>> directory = dict() >>> directory[('Taylor', 'Swift')] = 100 >>> print(directory) {('Taylor', 'Swift'): 100}
The element can be any type. The empty is ().
Features: Ordered, Immutable, Repeatable
Index and slice are the same with that of lists.
You cannot modify the elements of a tuple, but you can replace one tuple with another.
Comparing, multiple assignment, in operator
Tuples can be keys of a dictionary.
container | Feature | |
---|---|---|
List | [] | ordered; mutable; repeatable |
Tuple | () | ordered; immutable; repeatable |
Dictionary | {} | not ordered; key-value pairs and values are mutable, keys are not; values are repeatable, keys are not |
Values are immutable. Thus, numbers, strings, tuples are immutable. Lists, dictionaries are mutable.
What does it mean for immutable or mutable? Assignment, Modification, Reference
1. what is assignment? variable → computer memory → object
2. Modification
>>> x = "abc" >>> x = "def"
a. make a new assignment
>>> x = [1,2,3] >>> x = [4,5,6]
b. make a modification by methods for lists. You do not change the address.
>>> x = [1,2,3] >>> del x[2] >>> del x[1] >>> del x[0] >>> x.append(4) >>> x.append(5) >>> x.append(6)
3. Reference
>>> x = "abc" >>> y = x >>> x = "def" >>> print(y) "abc"
>>> x = [1,2,3] >>> y = x >>> del x[2] >>> x.append(4) >>> print(y) [1,2,4]
>>> x = [1,2,3] >>> y = x[:] >>> del x[2] >>> x.append(4) >>> print(y) [1,2,3]