Table of Contents
Python dictionary
In this tutorial, we will discuss the dictionary in the python programming language.
Dictionary is a special type of variable in python. It is an unordered collection of items, it has a pair of items, key and value. When creating the dictionary, we can place items inside of the dictionary using curly braces{} and separated by a comma.
Every item has a key and the corresponding value expressed as a pair key: value
How to create the dictionary
ProgrammingLanguages={}
ProgrammingLanguages[“php”]=”Hyper text Preprocessor”
ProgrammingLanguages[“htm”]=”Hyper text markup language”
ProgrammingLanguages[“css”]=”cascading style sheet”
ProgrammingLanguages[“js”]=”Java script”
How to accessing Dictionary
How to print all of element of dictionary
print(ProgrammingLanguages) //print all element of dictionary
Output
{‘php’: ‘Hyper text Preprocessor’, ‘html’: ‘Hyper text markup language’, ‘css’: ‘cascading style sheet’, ‘js’: ‘Java script’}
Print every element of using name instead index value or key value
Output //print every element of dictionary using keys
Hypertext Preprocessor Hypertext markup language cascading style sheet Java script
How to update an item of dictionary
If we want to update items to the dictionary, we can use an assignment operator. An example is given below
When the above code is executed, it produces the following results
{'age': 45, 'name': 'saman'} // before update {'age': 34, 'name': 'saman'} //after update How to add the item of dictionary
If we want to add items to the dictionary, we can use the assignment operator. Example is given below
When the above code is executed, it produced the following results
{'age': 45, 'name': 'saman'} // before add {'age': 45, 'name': 'saman', 'address': 'Jaffna'} //after add
How to remove the item of dictionary
If we want to remove items from the dictionary, we can use pop() operator. Example is given below
{'age': 45, 'name': 'saman', 'address': 'colombo'} 45 {'name': 'saman', 'address': 'colombo'}
{'age': 45, 'name': 'saman', 'address': 'colombo'} ('age', 45) {'name': 'saman', 'address': 'colombo'}
{1: 1, 2: 3, 3: 6, 4: 10, 5: 15} {1: 1, 2: 3, 3: 6, 5: 15} {}