Python Dictionary

Python’s efficient key/value hash table structure is called a “dictionary” or “dict”. Major difference between list and dictionary is that index is always numeric in list whereas in dictionary it can be of any data type.The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, … }. The “empty dict” is just an empty pair of curly braces {}.


>>> dict={}
>>> dict
>>> dict['a']="blue"
>>> dict['b']="sky"
>>> dict['c']="earth"
>>> dict
{'a': 'blue', 'b': 'sky', 'c': 'earth'}
>>> dict['a']
>>> type(dict)
<class 'dict'>
>>> dict={'a':'sky','b':'blue'} #other way to create dictionary
>>> dict
{'a': 'sky', 'b': 'blue'}

How to display key and values

>>> for k, v in dict.items(): print(k,'>',v) 
a > blue
b > sky
c > earth
>>> for a in dict.values(): print(a)
>>> for b in dict.keys(): print(b)

changing values and removing values

>>> dict
{'a': 'blue', 'b': 'sky', 'c': 'earth'}
>>> dict['a']="black" 
>>> dict
{'a': 'black', 'b': 'sky', 'c': 'earth'}
>>> dict.pop('a')
>>> dict
{'b': 'sky', 'c': 'earth'}
>>> del dict['b']
>>> dict
{'c': 'earth'}
>>> dict.clear()
>>> dict

Leave a Reply

Your email address will not be published. Required fields are marked *