Table of Contents
show
About Dictionary
- Dictionary is an unordered collection of key-value pairs
- When we have the large amount of data, the dictionary data type is used
- Keys and values can be of any type in a dictionary
- Items in dictionary are enclosed in the curly-braces { } and separated by commas (,)
- A colon (:) is used to separate key from value
- A key inside the square brackets [ ] is used for accessing the dictionary items
- Dictionaries are accessed via
- The keys
- The values
- Items (key – value pairs)
Operations
Creating a Dictionary
Creating the dictionary with elements of different data types
Example
>>> first_dict = {1:"Apple",2:"Mango",3:"Banana"}
>>> print(first_dict)
{1: 'Apple', 2: 'Mango', 3: 'Banana'}
Indexing
Access the items of a dictionary by referring to its key name inside square brackets
Example
>>> print(first_dict[1])
Apple
Change values
Change the value of a specific item by referring to its key name
Example
>>> first_dict[2] = "orange"
>>> print(first_dict)
{1: 'Apple', 2: 'orange', 3: 'Banana'}
Printing keys
Print all key names in the dictionary one by one
Example
>>> print(first_dict.keys())
dict_keys([1, 2, 3])
Printing values
Print all values in the dictionary one by one
Example
>>> print(first_dict.values())
dict_values(['Apple', 'Mango', 'Banana'])
Views: 5