Creating Dictionaries
A Python dictionary is created by enclosing a comma-separated list of key-value pairs within curly braces {}
. Each key-value pair is separated by a colon :
.
Python
# Empty dictionary
empty_dict = {}
# Dictionary with elements
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
Accessing Dictionary Elements
- You can access the value associated with a key using square brackets
[]
.
Python
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(person['name']) # Output: Alice
- Besides using square brackets, you can also use the
get()
method to access values. This method is safer because it returns a default value if the key is not found.
Python
person = {'name': 'Alice', 'age': 30}
print(person.get('address', 'Unknown')) # Output: Unknown
Important points:
- Keys in a dictionary must be unique and immutable (strings, numbers, or tuples).
- The order of elements in a dictionary is not guaranteed (until Python 3.7).
- Trying to access a non-existent key will raise a
KeyError
. - Dictionaries are mutable, so you can add, modify, or delete key-value pairs after creation.
How do you create an empty dictionary?
Use {}
to create an empty dictionary.
Can a dictionary contain duplicate keys?
No, dictionary keys must be unique.
Can I create a dictionary from a list of tuples?
Yes, using the dict()
constructor.
How do you access a value in a dictionary?
Use square brackets []
with the key.
What happens if you try to access a non-existent key?
It raises a KeyError
.
Are dictionaries ordered in Python?
In Python 3.7 and later, dictionaries maintain insertion order.
Can I use a list as a key in a dictionary?
No, because lists are mutable.
How do you remove a key-value pair from a dictionary?
Use the del
keyword or the pop()
method.
What is a dictionary comprehension?
A concise way to create dictionaries using a similar syntax to list comprehensions.
How do you create a dictionary comprehension?
Use curly braces {}
and specify key-value pairs within the expression.