Dictionaries in Python

dictionaries_in_python

Skill - Dictionaries in Python

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

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

Main Code

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


Online Interpreter

You can run these codes online at https://www.programiz.com/python-programming/online-compiler/


Table of Contents

Comments