Few mistakes when using Python dictionary
Usually, A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. Each key-value pair in a Dictionary is separated by a ‘colon’, whereas each key is separated by a ‘comma’.
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
print (my_dict)
|
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
We generally use dictionaries to access the items with its key value, inside square brackets.
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
print (my_dict[ 1 ])
print (my_dict[ 2 ])
print (my_dict[ 3 ])
|
The common operations of dictionaries are:
- To get the values of the dictionary we use values() method.
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
print (my_dict.values())
|
Output:
dict_values(['Geeks', 'For', 'Geeks'])
- To get the keys of the dictionary we use keys() method.
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
print (my_dict.keys())
|
Output:
dict_keys([1, 2, 3])
- To add a new entry into the dictionary
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
my_dict[ 4 ] = 'Python'
print (my_dict)
|
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks', 4: 'Python'}
- To change the value of the entry
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
my_dict[ 3 ] = 'Python'
print (my_dict)
|
Output:
{1: 'Geeks', 2: 'For', 3: 'Python'}
- To delete an entry from dictionary
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
del my_dict[ 3 ]
print (my_dict)
|
Output:
{1: 'Geeks', 2: 'For'}
- To copy the dictionary
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
my_dict1 = my_dict
print (my_dict1)
|
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
- To remove all entries.
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
my_dict.clear()
print (my_dict)
|
- To find the number of entries.
my_dict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
z = len (my_dict)
print (z)
|
Common mistakes while using dicts and overcomes
- To access the value of the key, we generally use dict_name[key_name] instead we should use get() method to get rid of the exceptions thrown all throughout your code.
- To update the value of the key, we generally use dict_name[key_name]=’new_value’ instead we should update(key=value) method to get rid of the exceptions thrown all throughout your code.
- To copy the dictionary, we generally use dict_name = new_dict_name instead we should use copy() method to get rid of the exceptions thrown all throughout your code.
When not to use dicts
- Dicts are useful but they’re not the only associative array structure in Python. Often there is a more specialised container type like set, tuple etc.
- Numeric values with different types can be equal (e.g. 1 == 1.0), in which case they represent the same key.
Last Updated :
06 Mar, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...