Tuples and Dictionaries
Tuples and Dictionaries
• Tuples are very similar to lists, but they are immutable (i.e.,
unchangeable)
In fact, Python has only these two built-in functions that can be used
on tuples
Towards Dictionaries
• Lists and tuples hold elements with only integer indices
45 “Coding” 4.5 7 89
0 1 2 3 4
Integer
Indices
• So in essence, each element has an index (or a key) which can only be
an integer, and a value which can be of any type (e.g., in the above
list/tuple, the first element has key 0 and value 45)
• What if we want to store elements with non-integer indices (or keys)?
Dictionaries
• In Python, you can use a dictionary to store elements with keys of any
types (not necessarily only integers like lists and tuples) and values of
any types as well
45 “Coding” 4.5 7 89
“NUM” 1000 2000 3.4 “XXX”
• Can be indexed but only through keys (i.e., dic2[“a”] will return 1 but dic2[0]
will return an error since there is no element with key 0 in dic2 above)
Dictionaries
• In summary, dictionaries:
• CANNOT be concatenated
• CANNOT be repeated
• Can be nested (e.g., d = {"first":{1:1}, "second":{2:"a"}}
• Can be passed to a function and will result in a pass-by-reference and not
pass-by-value behavior since it is immutable (like lists)
def func1(d):
d["first"] = [1, 2, 3]
Output:
dic = {"first":{1:1}, "second": {'first': {1: 1}, 'second': {2: 'a'}}
{2:"a"}} {'first': [1, 2, 3], 'second': {2: 'a'}}
print(dic)
func1(dic)
print(dic)
Dictionaries
• In summary, dictionaries:
• Can be iterated over
dic = {"first": 1, "second": 2, "third": 3}
for i in dic:
print(i)
1
Output: 2 Values can be accessed via indexing!
3
Adding Elements to a Dictionary
• How to add elements to a dictionary?
• By indexing the dictionary via a key and assigning a corresponding value
dic = {"first": 1, "second": 2, "third": 3}
print(dic)
dic["fourth"] = 4
print(dic)
Function Description
dic.clear() Removes all the elements from dictionary dic
dic.copy() Returns a copy of dictionary dic
dic.items() Returns a list containing a tuple for each key-value pair in
dictionary dic
dic.get(k) Returns the value of the specified key k from dictionary dic
dic.keys() Returns a list containing all the keys of dictionary dic
dic.pop(k) Removes the element with the specified key k from
dictionary dic
Dictionary Functions
• Many other functions can also be used with dictionaries
Function Description
dic.popitem() Removes the last inserted key-value pair in dictionary dic
dic.values() Returns a list of all the values in dictionary dic
Next Lecture…
• Practice on Tuples and Dictionaries