No Fluff Guide to Python - P7 - Dictionary

 

Dictionary

  • Imagine you have a phone book. 
    • You can look up a person's name 
    • find their phone number. 
    • You can also add new people to the phone book 
    • remove people from the phone book.

A Python dictionary is like a phone book. 

  • You can store any kind of data in a dictionary
    • like names, phone numbers, and addresses. 
  • You can also access the data in a dictionary using a key.
  • To create a dictionary, you use the {} curly braces. 
  • Structured in a Key Value pair
    • "Key": "Value"

Create a dictionary, name and age

dict = {
"name" : "vish",
"age"
: 30
}

 Key: Value

 Keys = IDs 

animals = {
    "cat": "meow",
    "dog": "woof",
    "duck": "quack",
    "chicken": "cluck"
    "chicken": "click" ❌ }

#Dictionary keys do not allow duplicates

 

You can access any particular value:

print(animals['duck'])

Output: quack

 

 Print all keys:

dict1={"key1":1,"key2":"value2",3:"value3"}
print(dict1.keys())  
    # all the keys are printed 
Output:

dict_keys(['key1', 'key2', 3])

 

Print all values:

print(dict1.values())
    # all the values are printed

 Output:

dict_values([1, 'value2', 'value3']) 

 


Check Existence:

  • in operator
  • check if a key is in a dictionary

dict = {
"name" : "vish",
"age"
: 30
}

if "name" in my_dict:
    print("The key 'name' exists in the dictionary.")

if "job" in my_dict:
    print("The key 'job' does not exist in the dictionary.")


in operator works for Lists, sets and strings too:

my_list = [1, 2, 3, 4, 5]

if 3 in my_list:
    print("The element 3 exists in the list.")


Set:
my_set = {1, 2, 3, 4, 5}

if 3 in my_set:
    print("The element 3 exists in the set.")


String:

my_string = "Do one thing every day that scares you.!"

if "one" in my_string:
    print("The substring 'one' exists in the string.")


 

Updates:

dict1["key1"]="replace_one"  
    # value assigned to key1 is replaced print(dict1)

#Output #{'key1': 'replace_one', 'key2': 'value2', 3: 'value3'
 print(dict1["key1"])

#Output #replace_one

 

dict1={
    "fruit1"
:"apple",
    "fruit2":"banana",
    "veg1":"tomato"
}
dict1.update({"veg2":"chilli"})  
        # updates the dictionary at the end print(dict1)


#Output #{
    'fruit1'
: 'apple',
    'fruit2'
: 'banana',
    'veg1'
: 'tomato',
    'veg2'
: 'chilli'





dict1.pop("veg2") print(dict1) #Output
#{
    'fruit1'
: 'apple',
    'fruit2'
: 'banana',
    'veg1'
: 'tomato'
}

 

 

Nested Dictionaries

  • Dictionary within another dictionary
  • useful for organizing data into hierarchical structure
  • example:
    • Dictionary of countries containing
      • dictionary of cities


countries = {

  "USA": {
    "capital": "Washington, D.C.",
    "population": 332000000,
  },

  "Canada": {
    "capital": "Ottawa",
    "population": 38000000,
  },

}


To access the value of a key in a nested dictionary, you can use the square brackets ([]) operator multiple times. For example, the following code prints the capital city of the USA:

print(countries["USA"]["capital"])




List of Dictionaries

  • a list containing dictionaries
  • storing related information
  • example:
    • list of all students
      • each represented by a dictionary of related info

students = [

  {
    "name": "Her",
    "age": 20,
    "gpa": 3.5,
  },

  {
    "name": "Him",
    "age": 21,
    "gpa": 3.8,
  },

]


To access the value of a key in a dictionary in a list of dictionaries, you can use the square brackets ([]) operator twice. For example, the following code prints the name of the first student in the list:
print(students[0]["name"])



Dictionaries of Lists

  • dictionary that maps Keys: Lists
  • useful for storing collection of related data items
    • organized into groups
  • Dictionary of all countries
    • list of languages spoken


countries = {
    "India": ["Hindi", "English"],
    "USA": ["English", "Spanish"],
    "China": ["Mandarin", "Cantonese"],
    "Japan": ["Japanese", "English"],
}


To access the value of a key in a dictionary of lists, you can use the square brackets ([]) operator twice. For example, the following code prints the list of languages in India:
print(countries["India"])



Real-world examples

In a social media platform, a dictionary can be used to store the posts of a user. The keys can be the post IDs and the values can be the post content.

Storing User Posts:

Each user's posts can be stored in a dictionary, where the keys are the post IDs and the values are the post content. This allows the platform to efficiently retrieve and display a user's posts when they visit their profile or when their posts appear in their friends' feeds.

user_posts = {
    "post_1": {
        "content": "I'm having a great time at the beach!",
        "timestamp": "2023-08-22T14:30:00Z",
        "likes": 100,
        "comments": [
            {
                "author": "Amit",
                "content": "Nice photo!"
            },
            {
                "author": "Radhe",
                "content": "I wish I was there!"
            },
        ]
    },
    "post_2": {
        "content": "Just finished reading a great book!",
        "timestamp": "2023-08-20T10:00:00Z",
        "likes": 50,
        "comments": [
            {
                "author": "Mohan",
                "content": "What book is it?"
            },
            {
                "author": "Rakesh",
                "content": "I've heard good things about that book!"
            },
        ]
    },
}


Storing User Profiles:

Each user's profile information can also be stored in a dictionary, where the keys are the user IDs and the values are the profile information. This information can include the user's name, profile picture, bio, and other relevant details.

user_profiles = {
    "user_1": {
        "name": "John Doe",
        "profile_picture": "profile_picture.jpg",
        "bio": "I'm a software engineer and I love to travel.",
        "friends": ["user_2", "user_3"],
    },
    "user_2": {
        "name": "Jane Smith",
        "profile_picture": "profile_picture.png",
        "bio": "I'm a marketing manager and I love to cook.",
        "friends": ["user_1", "user_3"],
    },
    "user_3": {
        "name": "Michael Jones",
        "profile_picture": "profile_picture.gif",
        "bio": "I'm a graphic designer and I love to play video games.",
        "friends": ["user_1", "user_2"],
    },
}

 

 

Sorting the Dictionary:

  • We have a dictionary called iphones that 
    • contains information about different iPhone models. 
  • Each model has two keys: 
    • width and height
  • which represent the width and height of the phone's screen in pixels.
iphones = {
    "iPhone 12": {
        "width": 828,
        "height": 1792
    },
    "iPhone 12 mini": {
        "width": 750,
        "height": 1542
    },
    "iPhone 11 Pro Max": {
        "width": 1242,
        "height": 2688
    }
    }
};


To sort the dictionary by the width key, we can use the sorted() function. The sorted() function takes a list or dictionary as its first argument and a key function as its second argument. The key function is used to extract the value that we want to sort by from each element in the list or dictionary.

sorted_iphones = sorted(iphones, key=lambda x: iphones[x]["width"])


print(sorted_iphones)

Output:
['iPhone 12 mini', 'iPhone 12', 'iPhone 11 Pro Max']

The lambda function 

  • used to define the key function. 
  • takes one argument, phone 
    • which represents each element in the iphones dictionary. 
  • Inside the lambda function, 
    • we use the phone["width"] expression 
    • to extract the width value from the phone dictionary. 
  • The sorted() function will return a new list of tuples
    • where each tuple contains a key-value pair from the iphones dictionary. 
  • The tuples will be sorted in ascending order based on the width value.


Dictionary Iteration:

You can then use these names to traverse the original Dictionary.


for
phone in sorted_iphones:     print(iphones[phone])

Output:

{'width': 750, 'height': 1542}
{'width': 828, 'height': 1792}
{'width': 1242, 'height': 2688}



animals = {
    "cat": "meow",
    "dog": "woof",
    "duck": "quack",
    "chicken": "cluck"
}


for key, value in animals.items():
    print(key + " does " + value)

Output:

cat does meow
dog does woof
duck does quack
chicken does cluck


For these simple dictionaries, you can sort them directly using sorted()

animals = {
    "cat": "meow",
    "dog": "woof",
    "duck": "quack",
    "chicken": "cluck"
}


for name in sorted(animals.keys()):
    print(name )

Output:

cat
chicken
dog
duck


That covers all the most important tasks related to dictionary.

Until Next Time!!

 

Comments

Popular posts from this blog

Index Clean-Up Scripts

forgot sa password and no logins are added

The SQL Server DBA’s Guide to Teradata