
Python dictionary is a kind of hash-table type where it has key value. A Dictionary contains items separated by commas and enclosed within square curly braces ({ })
. It is a collection of data which is changeable, indexed, and unordered. Python Dictionary does not have duplicate members.
Declaring Dictionary in Python
We can declared dictionary in two different ways:
# First Way dict1 = {} dict1['one']="one" dict1[1]=1 # Second Way dict2 = {'two':'two',2:2}
Note – The plus (+) sign is the concatenation operator and the asterisk (*) is the repetition operator. For example −
dict1 = {} dict1['one']="one" dict1[1]=1 dict2 = {'two':'two',2:2} print(dict1) print(dict2) print(dict1["one"]) print(dict1[1]) print(dict2.keys()) print(dict2.values())
It will give output like this
>>> print(dict1) {1: 1, 'one': 'one'} >>> print(dict2) {2: 2, 'two': 'two'} >>> print(dict1["one"]) one >>> print(dict1[1]) 1 >>> print(dict2.keys()) [2, 'two'] >>> print(dict2.values()) [2, 'two']
Whats Next – Python Casting