Dictionaries

Python basics

Python
Basics
Author

Kunal Khurana

Published

October 6, 2023

Learning outcomes

A dictionary in Python is a collection of key-value pairs. 1. looping through a dictionary 2. work with information stored in a dictionary 3. access and modify individual elements in a dictionary 4. nest multiple dictionaries in a list, nest lists in a dictionary, and nest a dictionary inside a dictionary

printing specific values from a dictionary

d_0= {'colour' : 'verte', 'point' : 5}

access = d_0['point'] #square brackets to access values
print(f"You have earned {access} points!")
You have earned 5 points!

adding key value pairs to dictionaries

d_0['tout va bien'] = 0
d_0['oui, ça va'] = 1
print(d_0)
{'tout va bien': 0, 'oui, ça va': 1}

modifying values in dicitonaries

d_0 = {'colour' : 'green'}    #curly brackets
print(f"The new colour is {d_0['colour']}.")
The new colour is green.
d_0 = {'colour' : 'marron'}
print(f"The changed colour is {d_0['colour']}.")  #square brackets for accessing specific elements
The changed colour is marron.

removing key-value pairs


print(d_0)
{'tout va bien': 0, 'oui, ça va': 1}
print(d_0)
{'tout va bien': 0, 'oui, ça va': 1}

choosing the value based on key pair

favorite_language = {
    'kunal': 'français',
    'ritika' : 'espagneol',
    'kartik' : 'russe',
    'vaibhav' : 'almande'
}
language = favorite_language['kunal'].title()
print(f"Kunal's favorite lanuage is {language}.")
Kunal's favorite lanuage is Français.

Remark*- consider using get method to obtain the value of the non assigned value pair

Looping through dictionary

user_0 = {'dob' : 'nov 1995',
         'birth_place' : 'gugaron', 
         'education' : 'masters',
         'children' : '2', 
         }

for key, value in user_0.items():
    print(f"\nKey: {key}")
    
    print(f"Value: {value}")

Key: dob
Value: nov 1995

Key: birth_place
Value: gugaron

Key: education
Value: masters

Key: children
Value: 2
print(d_0)
{'tout va bien': 0, 'oui, ça va': 1}

Using keys() mehtod for looping

favorite_language
for name in favorite_language.keys():
    print(name.title())
Kunal
Ritika
Kartik
Vaibhav
for language in favorite_language.values():
    print(language.title())
Français
Espagneol
Russe
Almande

Using keys method…

if 'raghav' not in favorite_language.keys():
    print("Raghav, please take your poll!")
Raghav, please take your poll!

Looping with keys method in a particular* method

for name in sorted(favorite_language.keys()):
    print(f"{name.title()}, thank you for taking the poll!")
Kartik, thank you for taking the poll!
Kunal, thank you for taking the poll!
Ritika, thank you for taking the poll!
Vaibhav, thank you for taking the poll!

Adding keys values with update method()

favorite_language.update({'vaisahli' : 'français'})
favorite_language
{'kunal': 'français',
 'ritika': 'espagneol',
 'kartik': 'russe',
 'vaibhav': 'almande',
 'vaisahli': 'français'}

Using set method to evit repetition

for language in set(favorite_language.values()):
    print(language.title())
Russe
Almande
Espagneol
Français

Nesting - for multiple dictionaries

print(user_0)
print(d_0)
print(favorite_language)
{'dob': 'nov 1995', 'birth_place': 'gugaron', 'education': 'masters', 'children': '2'}
{'tout va bien': 0, 'oui, ça va': 1}
{'kunal': 'français', 'ritika': 'espagneol', 'kartik': 'russe', 'vaibhav': 'almande', 'vaisahli': 'français'}

Using for loop to print all the dictionaries together

combined = [user_0, d_0, favorite_language]

for tout in combined:
    print(tout)
{'dob': 'nov 1995', 'birth_place': 'gugaron', 'education': 'masters', 'children': '2'}
{'tout va bien': 0, 'oui, ça va': 1}
{'kunal': 'français', 'ritika': 'espagneol', 'kartik': 'russe', 'vaibhav': 'almande', 'vaisahli': 'français'}

Nesting a list inside a dictionary

programming_languages = {'kunal' : ['python', 'latex', 'html', 'java'],
                        'john' : ['html', 'c', 'C++'],
                        'gofi' : ['java', 'python', 'R', 'html']}

for name, languages in programming_languages.items():  #use items to iterate thorough dictionary items
    print(f"\n{name.title()}'s favorite languages are:")
    for language in languages:
        print(f"\t{language.title()}")

Kunal's favorite languages are:
    Python
    Latex
    Html
    Java

John's favorite languages are:
    Html
    C
    C++

Gofi's favorite languages are:
    Java
    Python
    R
    Html

Nesting a dictionary inside a dictionary and looping

users = {
    'kkhurana' : {
        'first' : 'kunal',
        'last' : 'khurana', 
        'location': 'montréal',
        },
    
        'asharma' : {
            'first': 'anita',
            'last': 'sharma',
            'location': 'sudbery'
        },
    
    'jarora' : {
        'first' : 'jatin',
        'last' : 'arora',
        'location' : 'perth'
    },
    }
users
{'kkhurana': {'first': 'kunal', 'last': 'khurana', 'location': 'montréal'},
 'asharma': {'first': 'anita', 'last': 'sharma', 'location': 'sudbery'},
 'jarora': {'first': 'jatin', 'last': 'arora', 'location': 'perth'}}
for username, user_info in users.items():
    print(f"\nUsername: {username}")
    full_name = f"{user_info['first']} {user_info['last']}"
    location = user_info['location']
    
    print(f"\tFull name: {full_name.title()}")
    print(f"\tLocation: {location.title()}")

Username: kkhurana
    Full name: Kunal Khurana
    Location: Montréal

Username: asharma
    Full name: Anita Sharma
    Location: Sudbery

Username: jarora
    Full name: Jatin Arora
    Location: Perth