Understanding python dictionaries

Jayashree domala
2 min readSep 4, 2020

A guide to learn about dictionaries in python

Dictionaries are unordered mappings for storing objects. They store objects using a key-value pairing . This pairing allows users to quickly grab objects without knowing the index as it is in the case of lists.

The syntax to denote dictionaries is {} and colon “:” is used to denote the keys and their associated values.

{‘python’:1, ‘java’:2}

Dictionaries use the concept of mapping. Mappings are a collection of objects that are stored by a key, unlike a sequence that stored objects by their relative position. This is an important distinction, since mappings won’t retain order since they have objects defined by a key.

>>> dict1 = {'jay':2, 'shiv':5}
>>> dict1
{'jay': 2, 'shiv': 5}
>>> dict2 = {'python':'easy', 'java':'hard'}
>>> dict2
{'python': 'easy', 'java': 'hard'}
>>> dict3 = {1:'a', 2:'b'}
>>> dict3
{1: 'a', 2: 'b'}

Retrieval of value using key

>>> student_age ={'ajay':15, 'sham':21, 'sachin':11}
>>> student_age['ajay']
15

Its important to note that dictionaries are very flexible in the data types they can hold. Use dictionaries when you have to grab objects by their key name. It can be used when you need to do retrieval process without needing to know the location. But the disadvantage is that you cannot perform sorting operation.

>>> dict4 = {'a':23, 'b':[11,22,33], 'c':{'jack':22}}
>>> dict4
{'a': 23, 'b': [11, 22, 33], 'c': {'jack': 22}}
>>> dict4['b'][1]
22
>>> dict4['c']['jack']
22

Adding new key-value pairs

>>> dict5 = {'d':22.4, 'e':6}
>>> dict5['f'] = 20
>>> dict5
{'d': 22.4, 'e': 6, 'f': 20}

Change value

>>> dict5['f'] = 25
>>> dict5
{'d': 22.4, 'e': 6, 'f': 25}

Get all keys

>>> dict5.keys()
dict_keys(['d', 'e', 'f'])

Get all values

>>> dict5.values()
dict_values([22.4, 6, 25])

Get all pairings

>>> dict5.items()
dict_items([('d', 22.4), ('e', 6), ('f', 25)])

Nested dictionaries

>>> dict6 = {'key1':{'nestkey':{'subnestkey':'value'}}}
>>> dict6['key1']['nestkey']['subnestkey']
'value'

Refer to the notebook here.

Beginner-level books to refer to learn Python:

Advance-level books to refer to learn Python:

Reach out to me: LinkedIn

Check out my other work: GitHub

--

--

Jayashree domala

Self-driven woman who wishes to deliver creative and engaging ideas and solutions in the field of technology.