Sitemap
Naga Sudhir

Naga Sudhir

I like programming for fun and adding value to people's lives

Dictionaries in Python

2 min readAug 19, 2021

--

Press enter or click to view image in full size

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision

Get Naga Sudhir’s stories in your inbox

Join Medium for free to get updates from this writer.

A Dictionary contains a set of key-value pairs encapsulated in it

Create a dictionary

# create a dictionary
x = {'firstname': 'Nagasudhir', 'lastname': 'Pulla'}

Access a value using it’s key

# create a dictionary
xDict = {
'firstName': 'Nagasudhir',
'lastname': 'Pulla',
'age': 28,
'hobbies': ['tv', 'playing', 'youtube'],
'location': 'Mumbai',
'metaData': {
'proficiency': 'level 1',
'designation': 'Deputy Manager',
'department': 'IT',
'languages': ['C#', 'Javascript', 'HTML', 'CSS', 'typescript', 'python']
}
}
# access firstName value
print(xDict['firstName'])
# prints Nagasudhir
# access lastname value
print(xDict['lastname'])
# prints Pulla
outputStatement = 'The person name is {0} {1}.\nHe lives at {2}, his hobbies are {3}.\nHe knows {4}'\
.format(xDict['firstName'], xDict['lastname'], xDict['location'],
', '.join(xDict['hobbies']), ', '.join(xDict['metaData']['languages']))
print(outputStatement)
''' This should print
The person name is Nagasudhir Pulla.
He lives at Mumbai, his hobbies are tv, playing, youtube.
He knows C#, Javascript, HTML, CSS, typescript, python
'''

Check if dictionary has a key using “in” operator

# create a dictionary
x = {'firstname': 'Nagasudhir', 'lastname': 'Pulla'}
print('firstname' in x)
# prints True
print('somethingElse' in x)
# prints False

List out all the keys and values of a dictionary

# create a dictionary
x = {'firstname': 'Nagasudhir', 'lastname': 'Pulla'}
# print all the keys
print(list(x.keys()))
# prints ['firstname', 'lastname']
# print all the values
print(list(x.values()))
# prints ['Nagasudhir', 'Pulla']

Create / Edit values in a dictionary

# create a dictionary
x = {'firstname': 'Nagasudhir', 'lastname': 'Pulla'}
# change firstname
x['firstname'] = 'Sudhir'
# create a new property with key as 'age'
x['age'] = 28
# print the dictionary
print(x)
# prints {'firstname': 'Sudhir', 'lastname': 'Pulla', 'age': 28}

Video

Video for this post can be found here

--

--

Written by Naga Sudhir

0 followers

I like programming for fun and adding value to people's lives