Best Laptop
Python Dictionary and its functions

Python Dictionary and its functions

Hello friends, welcome to another session on Python Dictionary and its functions. In the last session, we discussed about Python Tuples. Dictionary is something which we have already used. A dictionary contains words and its meanings/synonyms alongside. In short, dictionary is a large sequence of ‘word-meaning’ pair. Python Dictionary on the other hand is a large sequence of ‘key-value’ pairs. Here you have a word which is key and a corresponding value for that key.

Example:  {‘car’:’four wheeler’, ‘bike’:’two wheeler’}

  • In above example, we have a dictionary having two sequences of key-value pair. First key is car and its value is four wheeler and second key is bike whose value is two wheeler.
  • Here we have to remember that we cannot have duplicate keys in a dictionary. Value can be repeating.
  • A dictionary is mutable in a way that we can change the value of a particular key. However we cannot change the key.
  • The key and value in dictionary are separated by colon(:)
  • Keys are case sensitive. Hence key ‘Car’ is different than ‘car’
  • All key-value pair are enclosed in curly brackets.

Examples of Python Dictionary and its functions:

1. Creating a dictionary

dict = {‘Python’:’3.0’,’Java’:’15.0.2’}

2. Creating an empty dictionary

empty = {}

3. Printing a dictionary

dict={'India':'New Delhi','USA':'Washington DC','China':'Beijing'}
print(dict)

4. Print value of selected keys – here we will use the key within square brackets along with dictionary name to print value. You will find connection with list and tuples where we use the indexes to print specific elements.

language = {'Python':'3.0','Java':'15.0.2'}
capital={'India':'New Delhi','USA':'Washington DC','China':'Beijing'}

print(language['Java'])
print(capital['USA'])

5. Keys are case sensitive. Hence using a different case for key will give error

capital={'India':'New Delhi','USA':'Washington DC','China':'Beijing'}

print(capital['USa'])
KeyError: 'USa'

6. We should not use a key which does not exist

capital={'India':'New Delhi','USA':'Washington DC','China':'Beijing'}

print(capital[‘Japan’])
NameError: name 'capital' is not defined

7. Keys and values can be integers or strings. String should be used with quotes(single and double quotes both will work).

dic={1:'One','Two':2}
print(dic)
print(dic[1])
print(dic['Two'])

8. How to check if a particular key is present in dictionary

dict={"India":"INR","USA":"USD","UK":"GBP"}
print(dict)
print('India' in dict)

9. Printing dictionary value if key exists– here we will create a dictionary. Then use a list having some elements. We will then browse the list and check if element is key in dictionary and print it if yes

dict={"India":"INR",
         "USA":"USD",
         "UK":"GBP"}
list=['India','China','UK']

for ele in list:
     if ele in dict:
         print('Value for key',ele,'is:',dict[ele])
     else:
         print(ele,'is not a key in dictionary')

Note the different way of defining the dictionary.

Browsing a Python Dictionary using different methods :

10. keys() method- this method browses through keys of the dictionary which can be used to print the values.

language={'India':'Hindi','Japan':'Japanese','USA':'English','China':'Mandarin'}
for element in language.keys():
     print(element,'->',language[element])

11. values() method- this method browses through the value of the dictionary which we can used to print the value

language={'India':'Hindi','Japan':'Japanese','USA':'English','China':'Mandarin'}
for element in language.values():
     print(element)

12. items() method- this method browses both keys and corresponding values which we can use to print both key and values. This method returns tuples where each tuple is a key-value pair.

number={'Two':4,'Three':9,'Four':16,'Five':25}
print(number.items())

13. items() method- using items() to print all the key-value pairs

number={'Two':4,'Three':9,'Four':16,'Five':25}
for a,b in number.items():
     print(a,'->',b)

14. sorted() method – Python dictionary prior to 3.6 version were not sorted which means that the order of dictionary output may not match the order in which the dictionary is defined. In order to sort the dictionary output, we use sorted method

language={'India':'Hindi','Japan':'Japanese','USA':'English','China':'Mandarin'}
for element in sorted(language.keys()):
     print(element,'->',language[element])

Modifying and deleting Python Dictionary values:

15. Changing the values of an existing key. We will use key with dictionary name and assign a new value

dict={'A':'apple','B':'banana','C':'dog'}
dict['C']='cat'
print(dict)

16. Adding a new key value pair. Here we have to use a non existent key

vowels={'A':'apple','e':'elephant','i':'ice cream','o':'owl'}
print(vowels)

vowels['u']='umbrella'
print(vowels)

17. update() method- Adding a new key value pair using update() method

vowels={'A':'apple','e':'elephant','i':'ice cream','o':'owl'}
print(vowels)

vowels.update({'u':'umbrella'})
print(vowels)

In this method, if we use an existing key, then it will behave like updating an existing key since we cannot have duplicate keys

18. Deleting a key value pair – here we have to use key with dictionary name. Remember that we have to use an existing key other wise we will get error

dict={'one':1,'two':2,'three':3}
print(dict)
del dict['three']
print(dict)

19. popitem() method- using this method, we can delete the last key value pair of dictionary

dict={'one':1,'two':2,'three':3}
print(dict)
dict.popitem()
print(dict)

20. len() method- getting length of dictionary. This will output the number of key-value pairs

dict={'one':1,'two':2,'three':3}
print(len(dict))

21. copy() method- copy an existing dictionary to a new dictionary

dict={'one':1,'two':2,'three':3}
dict_new=dict.copy()
print(dict_new)

22. clear an existing dictionary

dict={1:'one',2:'two'}
dict.clear()
print(dict)

23. convert tuple to a dictionary

tuple=((1,2),(3,4))
num_dict=dict(tuple)
print(num_dict)

24. combine two dictionaries into third one

dict1={1:'one',2:'two'}
dict2={3:'three',4:'four'}
dict3={}
for element in (dict1,dict2):
     dict3.update(element)
print(dict3)

Leave a Reply

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

Python 3.11.1 Features