Understanding python dictionaries

>>> 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
>>> 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'

Reach out to me: LinkedIn

Check out my other work: GitHub

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store