A dictionary, or map, consists of a collection of key-value pairs. The key is used to access the associated value. Keys must be unique within a dictionary. Values can be repeated.
dictionary['key'] = 'value'
value = dictionary['key']
del dictionary['key']
for key in dictionary:
print(key, dictionary[key]) # key, value
The syntax for creating maps or dictionaries in Python is:
empty_dictionary = {}
person = {
'name': 'John',
'age': 25
}
Dictionaries are useful in many cases. Below are some examples.
We can model objects and entities with key-value attributes:
product = {
'name': 'Smartphone',
'price': 500,
'brand': 'XYZ'
}
Counting occurrences of elements in sequences:
text = "Hello world world"
frequencies = {}
for word in text.split():
if word in frequencies:
frequencies[word] += 1
else:
frequencies[word] = 1
print(frequencies)
# {'Hello': 1, 'world': 2}
As a high performance alternative to lists and arrays.
Dictionaries are versatile data structures thanks to their fast access based on unique keys. They have uses in almost all programs, so mastering dictionaries is essential in any language.
Cheers for making it this far! I hope this journey through the programming universe has been as fascinating for you as it was for me to write down.
We’re keen to hear your thoughts, so don’t be shy – drop your comments, suggestions, and those bright ideas you’re bound to have.
Also, to delve deeper than these lines, take a stroll through the practical examples we’ve cooked up for you. You’ll find all the code and projects in our GitHub repository learn-software-engineering/examples.
Thanks for being part of this learning community. Keep coding and exploring new territories in this captivating world of software!
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.