Dictionaries are another data type that supports a {key: value} structure.
Creating a dictionary is as simple as placing items inside curly braces {}
separated by commas.
An item has a key
and a corresponding value
that is expressed as a pair (key: value).
While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.
To access the value, you use the key. Here’s an Python example:
Python Code:
1 2 3 4 |
food_dictionary = {"vegetable": "broccoli", "fruit": "apple"} print(food_dictionary["fruit"]) |
Output:
1 2 3 |
apple |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# get vs [] for retrieving elements my_dict = {'name': 'Duck', 'age': 23} # Output: Duck print(my_dict['name']) # Output: 23 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # Output None print(my_dict.get('address')) # KeyError print(my_dict['address']) |