Python Tuples and Dictionaries
Python Tuples and Dictionaries
Python Tuples and Dictionaries
AND DICTIONARIES
TUPLES
Tuples
Same as lists but
◦ Immutable
◦ Enclosed in parentheses
◦ A tuple with a single element must have a comma inside the parentheses:
◦ a = (11,)
Examples
>>> mytuple = (11, 22, 33)
>>> mytuple[0]
11
>>> mytuple[-1]
33
>>> mytuple[0:1]
(11,)
The comma is required!
Tuples are immutable
>>> mytuple = (11, 22, 33)
>>> saved = mytuple
>>> mytuple += (44,)
>>> mytuple
(11, 22, 33, 44)
>>> saved
(11, 22, 33)
Things that do not work
mytuple += 55
Traceback (most recent call last):Z
…
TypeError:
can only concatenate tuple (not "int") to tuple
◦ Can understand that!
Sorting tuples
>>> atuple = (33, 22, 11)
>>> atuple.sort()
Traceback (most recent call last):
…
AttributeError:
'tuple' object has no attribute 'sort'
>>> atuple = sorted(atuple)
>>> atuple Tuples are immutable!
[11, 22, 33]
If we have
age = {'Alice' : 25, 'Bob' :28}
then
age['Alice'] is 25
and
age[Bob'] is 28
Dictionaries are mutable
>>> age = {'Alice' : 25, 'Bob' : 28}
>>> saved = age
>>> age['Bob'] = 29
>>> age
{'Bob': 29, 'Alice': 25}
>>> saved
{'Bob': 29, 'Alice': 25}
Keys must be unique
>>> age = {'Alice' : 25, 'Bob' : 28, 'Alice' : 26}
>>> age
{'Bob': 28, 'Alice': 26}
Displaying contents
thisdict = { "Name": "ABC", "Gender": "Female", "age": 25 }
#Accessing Items
thisdict["age"] = 34
print(thisdict)
Updating directories
>>> age = {'Alice': 26 , 'Carol' : 22}
>>> age.update({'Bob' : 29})
>>> age
{'Bob': 29, 'Carol': 22, 'Alice': 26}
>>> age.update({'Carol' : 23})
>>> age
{'Bob': 29, 'Carol': 23, 'Alice': 26}
Returning a value
>>> age = {'Bob': 29, 'Carol': 23, 'Alice': 26}
>>> age.get('Bob')
29
>>> age['Bob']
29
Removing a specific
item (I)
>>> a = {'Alice' : 26, 'Carol' : 'twenty-two'}
>>> a
{'Carol': 'twenty-two', 'Alice': 26}
>>> a.pop('Carol’)
'twenty-two'
>>> a
{'Alice': 26}
Removing a specific
item (II)
>>> a.pop('Alice')
26
>>> a
{}
>>>
Clear Command
clear() keyword empties a dictionary
Make a copy of a dictionary with the copy() method
To understand whether a key element is present in a dictionary use in
keyword.
Remove a random item
>>> age = {'Bob': 29, 'Carol': 23, 'Alice': 26}
>>> age.popitem()
('Bob', 29)
>>> age
{'Carol': 23, 'Alice': 26}
>>> age.popitem()
('Carol', 23)
>>> age
{'Alice': 26}
Summary
Strings, lists, tuples, sets and dictionaries all deal with aggregates
Two big differences
◦ Lists and dictionaries are mutable
◦ Unlike strings, tuples and sets
◦ Strings, lists and tuples are ordered
◦ Unlike sets and dictionaries
Mutable aggregates
Can modify individual items
◦ x = [11, 22, 33]
x[0] = 44
will work