The python dictionary has a set of predefined methods used to perform various tasks in the dictionary. A dictionary stores a pair of values, one of which is the Key, and the other is the Key-value element.
What is a Python Dictionary?
A python dictionary is a collection of unordered items. Each of these items has a key/value pair. Using some of the built-in dictionary functions users can retrieve their desired key-value pairs.Â
How do you declare a Dictionary in Python?
A dictionary in Python is declared using curly braces. The key-value pairs are separated with commas.Â
For example:
Dict1 = {1: 'Have', 2: 'a', 3: 'Good', 4:'Day'}
print("\nDictionary having integer keys: ")
print(Dict1)
Dict1 = {'Name': 'Amy', 1: [0, 1, 2, 3, 4]}
print("\nDictionary having mixed keys: ")
print(Dict1)
Output:Â
Â
Dictionary having integer keys:
{1: 'Have', 2: 'a', 3: 'Good', 4:'Day'}
Dictionary having mixed keys:
{'Name': 'Amy', 1: [0, 1, 2, 3, 4]}
Is dictionary faster than list Python?
When compared to lists, finding elements in dictionaries is much faster. This is because dictionaries in Python look for key-value pairs using a hash table, where the lists look for the key-value pairs from the beginning of the list till the pairs are found.
How do you access a dictionary in python?
A dictionary uses keys to access the elements from the dictionary. The elements can be accessed using the get(). If the user is trying to access an element that does not exist, an error is generated.Â
Source Code
my_dict1 = {'name': 'Jacky', 'age': 25}
# Output: Jacky
print(my_dict1['name'])
# Output: 25
print(my_dict1.get('age'))
# If you try to access the keys that don't exist, an error will be generated
print(my_dict.get1('address'))
# KeyError
print(my_dict1['address'])
Output
Jacky
25
None
Traceback (most recent call last):
  File "", line 15, in
    print(my_dict['address'])
KeyError: 'address'
Leave a Reply