Python Dictionary

A Python dictionary is a collection of key-value pairs. It is an unordered data structure, meaning that the items are not stored in a specific order. The keys in a dictionary must be unique and of an immutable data type, such as a string or a number. The values can be of any data type, and they don’t have to be unique. You can create a dictionary in Python by enclosing a comma-separated list of key-value pairs in curly braces {}. You can also use the dict() function to create a dictionary. Here are some examples:

>>> colors = {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}
>>> numbers = dict(one=1, two=2, three=3)

You can access the values in a dictionary by using the keys. For example:

>>> colors['red']
'#FF0000'

You can also use the get() method to access the values in a dictionary. This method returns the value for the specified key, or a default value if the key is not found.

>>> colors.get('red', 'unknown')
'#FF0000'
>>> colors.get('orange', 'unknown')
'unknown'

You can add new key-value pairs to the dictionary using the assignment operator =. For example:

>>> colors['yellow'] = '#FFFF00'

You can remove key-value pairs from the dictionary using the del statement. For example:

>>> del colors['red']

You can loop through the keys in a dictionary using a for loop. For example:

>>> for key in colors:
>>>     print(key)
red
green
blue
yellow

You can also use the items() method to get a list of the key-value pairs in a dictionary. For example:

>>> for key, value in colors.items():
>>>     print(key, value)
red #FF0000
green #00FF00
blue #0000FF
yellow #FFFF00

Dictionaries are very useful when you need to store data in a flexible and organized way. They are also very efficient for retrieving data, since you can access the values using the keys. Dictionaries are an essential data structure in Python, and you will use them often in your programming projects.

Was this helpful?
[0]