Dictionary and Tuples Flashcards
What is the syntax for creating a tuple?
my_tuple = (1, 2, 3)
.
How to create a single-element tuple?
Add a trailing comma: my_tuple = ('item',)
.
What is the key difference between a list and a tuple?
Tuples are immutable; lists are mutable.
How to access an element in a tuple?
Use indexing: my_tuple[0]
(e.g., (1,2,3)[1]
→ 2
).
How to slice a tuple?
Use slicing: my_tuple[start:end:step]
(e.g., (1,2,3,4)[1:3]
→ (2,3)
).
What method counts occurrences of a value in a tuple?
.count(value)
(e.g., (1,2,2).count(2)
→ 2
).
What method returns the index of a value in a tuple?
.index(value)
(e.g., (1,2,3).index(2)
→ 1
).
How to concatenate two tuples?
Use +
(e.g., (1,2) + (3,4)
→ (1,2,3,4)
).
How to repeat a tuple?
Use *
(e.g., (1,2) * 2
→ (1,2,1,2)
).
How to convert a list to a tuple?
Use tuple()
: tuple([1,2,3])
→ (1,2,3)
.
How to unpack a tuple?
Assign to variables: a, b = (1, 2)
→ a=1
, b=2
.
question
answer
What is the syntax for creating a dictionary?
my_dict = {'key': 'value'}
.
How to access a value in a dictionary?
Use the key: my_dict['key']
(e.g., {'a':1}['a']
→ 1
).
How to add or update a key-value pair?
Assign directly: my_dict['new_key'] = 'new_value'
.
How to safely access a value without raising KeyError
?
Use .get(key)
(e.g., my_dict.get('key')
→ value
or None
).
What method removes a key and returns its value?
.pop(key)
(e.g., {'a':1}.pop('a')
→ 1
).
How to remove all items from a dictionary?
Use .clear()
: my_dict.clear()
→ {}
.
What method returns all keys in a dictionary?
.keys()
(e.g., {'a':1}.keys()
→ ['a']
).
What method returns all values in a dictionary?
.values()
(e.g., {'a':1}.values()
→ [1]
).
What method returns key-value pairs as tuples?
.items()
(e.g., {'a':1}.items()
→ [('a',1)]
).
How to check if a key exists in a dictionary?
Use in
: 'key' in my_dict
→ True
or False
.
How to merge two dictionaries?
Use .update()
: {'a':1}.update({'b':2})
→ {'a':1,'b':2}
.
How to create a dictionary from two lists?
Use zip()
: dict(zip(keys, values))
(e.g., dict(zip(['a'],[1]))
→ {'a':1}
).
How to create a dictionary with default values?
Use defaultdict
from collections
or .setdefault()
.
What is dictionary comprehension?
{k: v for k, v in iterable}
(e.g., {x: x*2 for x in range(3)}
→ {0:0,1:2,2:4}
).
How to copy a dictionary?
Use .copy()
: new_dict = my_dict.copy()
.