Revision:
In Python, lists, tuples, sets, and dictionaries are all built-in data structures, but they differ in mutability, ordering, and how they store data. Lists and dictionaries are mutable, tuples are immutable, and sets enforce uniqueness. Dictionaries store key–value pairs, while the others store single values.
List: [ ]
Tuple: ( )
Set: { } or set()
Dictionary: {key: value}
myList = [1,2,3,4,5]
[2*item for item in myList]
This a list comprehension, not a for loop.
In a for ... in loop, the colon (:) is mandatory because it introduces a block of indented code.
for item in myList:
print(2*item)
We can use any valid variable name instead of "item" in a for ... in loop or a list comprehension. The name is just a placeholder that represents each element in the sequence while iterating.
What is a Key–Value Pair?
A dictionary is like a real-world dictionary:
Key = the word you look up.
Value = the definition you get.
In Python:
Key must be unique and immutable (string, number, tuple).
Value can be anything (string, number, list, another dict, etc.).
person = {
"name": "Alice",
"age": 25,
"city": "Hong Kong"
}
"name" → key, "Alice" → value
"age" → key, 25 → value
"city" → key, "Hong Kong" → value
animalList = [('a', 'anteater'), ('b', 'bear'), ('c', 'cat'), ('d', 'dog')]
animals = {item[0]: item[1] for item in animalList}
animals
List of tuples
[('a', 'anteater'), ('b', 'bear'), ('c', 'cat'), ('d', 'dog')]
Each tuple has two elements:
item[0] → the key (like 'a')
item[1] → the value (like 'anteater')
Dictionary comprehension
{item[0]: item[1] for item in animalList}
Loops through each tuple in animalList.
Uses the first element (item[0]) as the key.
Uses the second element (item[1]) as the value.
{'a': 'anteater', 'b': 'bear', 'c': 'cat', 'd': 'dog'}
>>> animalList = [('a', 'anteater'), ('b', 'bear'), ('c', 'cat'), ('d', 'dog')]
>>> animals = {key: value for key, value in animalList}
... animals
...
{'a': 'anteater', 'b': 'bear', 'c': 'cat', 'd': 'dog'}
animals.items()
dict_items([('a', 'anteater'), ('b', 'bear'), ('c', 'cat'), ('d', 'dog')])
Asking Python to give you all the key–value pairs in the dictionary.
list(animals.items())
[('a', 'anteater'), ('b', 'bear'), ('c', 'cat'), ('d', 'dog')]
A list comprehension that builds a list of dictionaries from your animals dictionary
[{'letter': key, 'name': value} for key, value in animals.items()]
animals.items()
Produces key–value pairs like:
('a', 'anteater'), ('b', 'bear'), ('c', 'cat'), ('d', 'dog')
Looping with for key, value in animals.items()
Each iteration unpacks the tuple into key and value.
Dictionary inside the comprehension
For each pair, you create a new dictionary:
{'letter': key, 'name': value}
Result:
[{'letter': 'a', 'name': 'anteater'}, {'letter': 'b', 'name': 'bear'}, {'letter': 'c', 'name': 'cat'}, {'letter': 'd', 'name': 'dog'}]
Microsoft Copilot