How to create a dictionary?
* Creating a dictionary is as simple as placing items inside curly braces {} separated by a comma.
* An item has a key and the corresponding value expressed as a pair, key: value.
* While 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.
The syntax to define the dictionary is given below.
Syntax:
dict = {key1:value1, key2:value2, key3:value3,….}
# empty dictionary
dict = {}
# dictionary with integer keys
#{key:value}
items = {1: ‘apple’, 2: ‘ball’}
items is the name of the dictionary
where 1 and 2 are keys and “apple” and “ball” are values.
items = {1: 'apple', 2: 'ball'} print(type(items)) print("displaying items") print(items)
#Output <class 'dict'> displaying items {1: 'apple', 2: 'ball'} >>>
Example:
student={‘roll’:101,’name’:’Amit’,’per’:98}
student is the name of the dictionary
Where roll,name and per are keys and 101,Amit and 98 are values.
student={'roll':101,'name':'Amit','per':98} print(type(student)) print("displaying student details") print(student)
#Output <class 'dict'> displaying student details {'roll': 101, 'name': 'Amit', 'per': 98} >>>
Example:
Employee = {“Name”: “Sumit”, “Age”:9,”Salary”:25000, “Company”:”TCS”}
Employee is the name of the dictionary
Where Name,Age,Salary and company are keys and Sumit,9,25000 and TCS are values.
Employee = {"Name": "Sumit", "Age":9,"Salary":25000,"Company":"TCS"} print(type(Employee)) print("displaying Employee details") print(Employee)
#Output <class 'dict'> displaying Employee details {'Name': 'Sumit', 'Age': 9, 'Salary': 25000, 'Company': 'TCS'} >>>
Example:
# dictionary with mixed keys
dict = {‘name’: ‘Sunita’, 1: [2, 4, 3]}
dict = {'name': 'Sunita', 1: [2, 4, 3]} print(type(dict)) print("displaying dict details") print(dict)
#Output <class 'dict'> displaying dict details {'name': 'Sunita', 1: [2, 4, 3]} >>>
Python provides the built-in function dict() method which is also used to create dictionary. The empty curly braces {} is used to create empty dictionary.
# using dict()
# Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with dict() method subject = dict({1: 'C', 2: 'C++', 3:'Python', 4:'Java', 5:'Php'}) print("\nCreate Dictionary by using dict(): ") print(subject) # Creating a Dictionary # with each item as a Pair student = dict([(101, 'Amit'), (2, 'Kapil')]) print("\nDictionary with each item as a pair: ") print(student)
#Output Empty Dictionary: {} Create Dictionary by using dict(): {1: 'C', 2: 'C++', 3: 'Python', 4: 'Java', 5: 'Php'} Dictionary with each item as a pair: {101: 'Amit', 2: 'Kapil'} >>>