Python Dictionaries

Dictionaries are one of the most important data-structures of python.You can think dictionaries as a hash map.Data is stored in dictionaries as a key value pair.In this post,you will learn about python dictionaries,different ways of creating python dictionaries,various methods of dictionaries and different ways of accessing dictionary elements.

Creating Dictionary

Python dictionaries have a key and a value associated with that key.There are various ways in which we can create python dictionaries.Some of them are below:

Using {} brackets

you will learn about python dictionaries,different ways of creating python dictionaries,various methods of dictionaries and different ways of accessing dictionary elements.This is the simplest and very basic way in which we can create a python dictionary.Just put all the key:value pairs in {} bracket and this will create a dictionary.

alphabets={1:"A",2:"B",3:"C",4:"D"}
print(alphabets)

###OUTPUT###
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}

Using python’s dict() function

You can define python dictionary using pythons dict() function. dict() takes list of tuples,containing keys and values.

alphabet=dict([(1,'A'),(2,'B'),(3,'C'),(4,'D')])
print(alphabet)

###OUTPUT###
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}

Here is a cool thing about dict function.If keys or both keys and values are strings,we can pass tuples directly without enclosing it in list as a keyword=argument pairs.

#Key-Value both are string
alphabet1=dict(A='1',B='2',C='3',D='4')

#Only Key is of type string
alphabet2=dict(A=1,B=2,C=3,D=4)

print(alphabet1)
print(alphabet2)

###OUTPUT###
{'A': '1', 'B': '2', 'C': '3', 'D': '4'}
{'A': 1, 'B': 2, 'C': 3, 'D': 4}

Notice,the difference between the argument passed to dict methods in above two ways of defining dictionaries using dict method.We can not use above method,if keys are numeric.It will throw an error.

alphabet=dict(1='A',2='B',3='C',4='D')

###ERROR##
  File "<stdin>", line 1
SyntaxError: keyword can't be an expression

Because,keys are numeric we can not use the second method,we need to use first method of creating dictionaries using dict() method.

Using Dictionary comprehensions

You can use dictionary comprehensions to create dictionary in python.You can pass list enclosed in zip method which will return a zip type object and we can use this to create a python dictionary.

Example 1

alphabet={a:b for a,b in zip([1,2,3],['a','b','c'])}
print(alphabet)

###OUTPUT###
{1: 'a', 2: 'b', 3: 'c'}

Example 2

square={a:a*a for a in (1,2,3,4,5)}
print(square)

###OUTPUT###
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Using fromkeys() method

We can use pythons dict.fromkeys() method to create a dictionary. It returns a dictionary with the keys which you supplied as arguments.Syntax for creating dictionary using fromkeys() method is:

dict.fromkeys(keys,[values])

fromkeys() take a couple of arguments from which, keys are mandatory but values are optional.If you do not provide values,then values will be “None”. Lets see some ways of creating dictionaries using fromkeys() method.

Example 1

Lets see what happens when we create dictionary using fromkeys() method without values.

alphabets=dict.fromkeys([1,2,3,4,5])
print(alphabets)

###OUTPUT###
{1: None, 2: None, 3: None, 4: None, 5: None}

You can see that,if we do not provide values,every keys will be associated with None.Sometimes this method can be very useful.Suppose, we want to create a dictionary with keys ranging from 1 to 10 and for each key we want same value.

Example 2

alphabets=dict.fromkeys(range(1,11),"A")
print(alphabets)

###OUTPUT###

{1: 'A', 2: 'A', 3: 'A', 4: 'A', 5: 'A', 6: 'A', 7: 'A', 8: 'A', 9: 'A', 10: 'A'}

Accessing Dictionary Elements

There are various ways in which we can access dictionary elements.Some of them are listed below:

Accessing dictionary element using keys

We can access elements of dictionaries,using key indexing.

alphabet={1: 'a', 2: 'b', 3: 'c',4:'d',5:'e'}
alphabet[1]

###OUTPUT###
'a'

Accessing dictionary elements using loops

We can use loops to access dictionary elements.One thing we need to remember while using loops on dictionaries is that,loops iterate over the keys of dictionaries and if we want to access values of list,we can access it using dictionary_name[key].

alphabet={1: 'a', 2: 'b', 3: 'c',4:'d',5:'e'}
print(alphabet)

###OUTPUT###
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

for i in alphabet:
    print(i)
###OUTPUT###
1 2 3 4 5 ###Keys of dictionaries

for i in alphabet:
    print(alphabet[i])

###OUTPUT###
a b c d e ##Values

As you can see,when we iterate over dictionary using loop we can access only keys of dictionary.So,we need to use alphabet[i] to access values of dictionary.

Accessing dictionary element using .items() method

We can use .item() method on dictionary while iterating over it which will return key value pair as a tuple.

alphabet={1: 'a', 2: 'b', 3: 'c',4:'d',5:'e'}

for k,v in alphabet.items():
    print(k,v)

###OUTPUT###
1 a
2 b
3 c
4 d
5 e

Manipulating Dictionaries

Changing values of Dictionaries

We can change values of dictionaries in following ways.

fruits={1:'Apple',2:'Mango',3:'Banana',4:'Orange',5:'Pineapple'}
print(fruits)

###OUTPUT###
{1: 'Apple', 2: 'Mango', 3: 'Banana', 4: 'Orange', 5: 'Pineapple'}

###CHANGE 2 to Grapes###

fruits[2]='Grapes'

print(fruits)

###Notice 2 hanged to Grapes###
{1: 'Apple', 2: 'Grapes', 3: 'Banana', 4: 'Orange', 5: 'Pineapple'}

Adding new Key,Values to Dictionary

We can add new key value pairs to an existing dictionary,by directly supplying key and its corresponding value in following way:

fruits[6]='Kivi'

print(fruits)
###OUTPUT###
{1: 'Apple', 2: 'Grapes', 3: 'Banana', 4: 'Orange', 5: 'Pineapple', 6: 'Kivi'}

Deleting a Key,Value from Dictionary

del fruits[6]
print(fruits)

###keys and values(6:Kivi) got deleted##
{1: 'Apple', 2: 'Grapes', 3: 'Banana', 4: 'Orange', 5: 'Pineapple'}

Deleting only values corresponding to a key

fruits[1]=''
print(fruits)

###Empty value for key 1##
{1: '', 3: 'Banana', 4: 'Orange', 5: 'Pineapple'}

Deleting whole dictionary

del fruits
print(fruits)

###Error,as fruits got deleted###
NameError: name 'fruits' is not defined

Dictionary methods

popitem()

popitem() removes a random key-values pair from dictionary and returns it as a tuple.

fruits={1:'Apple',2:'Mango',3:'Banana',4:'Orange',5:'Pineapple'}
print(fruits.popitem())

###OUTPUT##
(5, 'Pineapple')

print(fruits)
###Pineapple got deleted##
{1: 'Apple', 2: 'Mango', 3: 'Banana', 4: 'Orange'}

keys()

keys() method return all keys of the dictionary as a list.

print(fruits.keys())

###OUTPUT###
dict_keys([1, 2, 3, 4])

print(list(fruits.keys()))

###OUTPUT###
[1, 2, 3, 4]

values()

values() method return all values of the dictionary as a list.

print(fruits.values())

###OUTPUT##
dict_values(['Apple', 'Mango', 'Banana', 'Orange'])

print(list(fruits.values()))

###OUTPUT###
['Apple', 'Mango', 'Banana', 'Orange']

items()

.item() method returns key value pair as a tuple.

print(fruits)
###OUTPUT###
{1: 'Apple', 2: 'Mango', 3: 'Banana', 4: 'Orange'}

###Using items() method##
print(fruits.items())
###OUTPUT##
dict_items([(1, 'Apple'), (2, 'Mango'), (3, 'Banana'), (4, 'Orange')])


print(list(fruits.items()))

###OUTPUT###
[(1, 'Apple'), (2, 'Mango'), (3, 'Banana'), (4, 'Orange')]

get()

get() method is used to get the values of key which is specifies in get method.If key exists,then corresponding values is returned else None is returned.

fruits={1: 'Apple', 2: 'Mango', 3: 'Banana', 4: 'Orange'}
print(fruits.get(1))

###OUTPUT##
'Apple'

print(fruits.get(5)) ##key 5 is not in fruits
###OUTPUT###
None

We can pass a default value ,which will be returned instead of None,if key is not in the dictionary.

print(fruits.get(5,"Key not found"))

###OUTPUT##
Key not found

update()

update method is used to update existing dictionaries. update method can be used to update existing dictionary by merging them with other dictionary or an iterable which have a key-value pair.

There are some points which we should remember,when using update method.

  • If key does not exists in old dictionary,then key-value pair is added to existing(old) dictionary.
  • If key exits in old dictionary,then,old value is replaced with new value from new dictionary(Duplicate keys are not allowed).
old_dict={1:"USA",2:"UK",3:"Russia",4:"UAE",5:"India}
new_dict={4:"France","6:"Australia"}

print(old_dict)
print(new_dict)

###OUTPUT###
{4: 'France', 6: 'Australia'}
{1: 'USA', 2: 'UK', 3: 'Russia', 4: 'UAE', 5: 'India'}

###Update old_dict with new_dict

old_dict.update(new_dict)
print(old_dict)

###OUTPUT##
{1: 'USA', 2: 'UK', 3: 'Russia', 4: 'France', 5: 'India', 6: 'Australia'}

You can see that,after we update old_dict with new_dict, Australia is added to old_dict,But,UAE is replaced with France.Why? Because,duplicate keys are not allowed in dictionary.So,when we tried to add Australia with key 6 to old_dict,it got added to old_dict as key 6 was not present in old_dict.But,when we tried to add France to old_dict with key 5,as key 5 was already present in old_dict,value of key 5(UAE) in old_dict got replaced with France.

We can pass iterables with key-value pairs to update method to update the dictionaries.

old_dict.update([(7,"China"),(8,"Italy")])
print(old_dict)

###OUTPUT##
{1: 'USA', 2: 'UK', 3: 'Russia', 4: 'France', 5: 'India', 6: 'Australia', 7: 'China', 8: 'Italy'}

That’s all about python dictionaries.I hope, I have covered almost everything which you should know about python dictionaries.If there are any suggestions or doubts,feel free to comment below.

Thank You.

Amarjeet

About Amarjeet

Amarjeet,BE in CS ,love to code in python and passionate about Machine Learning and Data Science. Expertsteaching.com is just a medium to share what I have learned till now with world.
Bookmark the permalink.

Leave a Reply

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