⬅ Previous Topic
SetsNext Topic ⮕
Stacks - LIFO Data Structure⬅ Previous Topic
SetsNext Topic ⮕
Stacks - LIFO Data StructureA dictionary is a data structure that stores data in the form of key-value pairs. Each key in the dictionary is unique and is used to access its corresponding value. Think of a dictionary like a real-world glossary or contact list: you look up a word (key) and find its meaning (value).
# Create an empty dictionary and add key-value pairs
dictionary = {}
dictionary["name"] = "Alice"
dictionary["age"] = 30
dictionary["city"] = "Wonderland"
print(dictionary)
Output:
{"name": "Alice", "age": 30, "city": "Wonderland"}
A dictionary uses a special structure called a hash table internally. This allows it to locate values very quickly using the keys.
Can dictionary keys be repeated?
Answer: No, keys must be unique. If you assign a new value to an existing key, it will overwrite the previous value.
# Access a value using its key
name = dictionary["name"]
print(name)
# Modify an existing value
dictionary["age"] = 31
print(dictionary["age"])
Output:
Alice 31
# Remove a key-value pair
remove dictionary["city"]
print(dictionary)
Output:
{"name": "Alice", "age": 31}
What happens if you try to access a key that doesn’t exist?
Answer: It will usually result in an error or a null/undefined value depending on the language or environment. Some implementations allow safe access with default values.
# Iterate over keys and values
for each key in dictionary:
value = dictionary[key]
print(key + ": " + toString(value))
Output:
name: Alice age: 31
Are dictionaries ordered?
Answer: In many modern implementations, yes – items retain the order they were added. But in some older or lower-level systems, order is not guaranteed.
Create a dictionary that stores student names as keys and their test scores as values. Then:
⬅ Previous Topic
SetsNext Topic ⮕
Stacks - LIFO Data StructureYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.