Python Collections: List, Tuple, Set,
Dictionary
Each section includes theory, creation patterns, common operations/methods,
arithmetic/aggregate functions, and traversal.
Contents
1. List
2. Tuple
3. Set
4. Dictionary
4. Dictionary
A dictionary maps keys to values. Keys must be hashable (immutable types like
str, int, tuple).
In [63]: # Values we want in memory
person = ["Hadi","Gupta",15, "Prayagraj","India",211001]
# Information about values called metadata
details = ["FName","LName",'age','city','country','pincode']
# Solution: Mapping
# (metadata --> data)
# (key --> value)
4.1 Creation
In [64]: # Create empty Dictionary
emptyDict = {}
print(emptyDict)
print(type(emptyDict))
print(len(emptyDict))
{}
<class 'dict'>
0
In [65]: # Using key:value pairs
person = {'name': 'Adam', 'lang': 'Python', 'age': 36}
print(person)
{'name': 'Adam', 'lang': 'Python', 'age': 36}
4.2 Access, Insert, Update
In [66]: # Accessing value with key
d = {'a': 1, 'b': 2}
print(d['a']) # direct access (KeyError if not found)
print([Link]('z')) # safe access with get method
1
None
In [67]: # Inserting a new Key with value (Extra)
d['c'] = 3 # insert key:'c' and assign it value:3
print(d)
{'a': 1, 'b': 2, 'c': 3}
In [68]: # Updating value of existing key
[Link]({'b': 20}) # update key:'b' with value 20
print(d)
{'a': 1, 'b': 20, 'c': 3}
4.3 Remove Items
In [69]: d = {'x': 1, 'y': 2, 'z': 3}
val = [Link]('y') # remove by key & return value
print("Original:",d," | Popped:",val)
k, v = [Link]() # remove & return an arbitrary item (LIFO in 3.7+)
print("Original:",d," | Pop Item:",(k,v))
Original: {'x': 1, 'z': 3} | Popped: 2
Original: {'x': 1} | Pop Item: ('z', 3)
In [70]: del d['x'] # delete by key using del command
print("remaining:", d)
remaining: {}
In [71]: # remove all elements
[Link]()
print("cleared:", d)
cleared: {}
4.4 Views & Traversal
In [72]: student = {'name': 'Robo', 'marks': 92, 'passed': True}
# Print all keys
print([Link]())
# Print all values
print([Link]())
# Print all key,value pairs
print([Link]())
dict_keys(['name', 'marks', 'passed'])
dict_values(['Robo', 92, True])
dict_items([('name', 'Robo'), ('marks', 92), ('passed', True)])
In [73]: # Traversal
for key in student:
print("key:", key)
for key, value in [Link]():
print(f"{key} -> {value}")
key: name
key: marks
key: passed
name -> Robo
marks -> 92
passed -> True
4.5 Arithmetic / Aggregate Functions
In [74]: prices = {'pen': 10, 'notebook': 35, 'eraser': 5}
print("len:", len(prices))
print("min key:", min(prices)) # lexicographic on keys
print("max key:", max(prices))
print("sum of values:", sum([Link]()))
len: 3
min key: eraser
max key: pen
sum of values: 50
4.7 Some Other Practise Examples
In [75]: data = {
"FName":"Hadi",
"LName":"Gupta",
'age':15,
'city':"Prayagraj",
'country':"India",
'pincode':211001
}
In [76]: data
Out[76]: {'FName': 'Hadi',
'LName': 'Gupta',
'age': 15,
'city': 'Prayagraj',
'country': 'India',
'pincode': 211001}
In [77]: # Accessing particualar value via key:pincode
data["pincode"]
Out[77]: 211001