Python 06

Python Dictionaries

The dictionaries are very useful if we want to create more complex data structures.

Dictionary structure

Imagine contacts from your phone. Or imagine when we create an account, we type in Id, password, phone number, etc.

person = {
  'name': 'Anton',
  'shirt': 'Black',
  'laptop': 'Apple',
}

To understand dictinaries in python, think the semantic meaning of word dictionary. It has key (word in dictionary) and value (description in dictionary) pair.

user = {
  'user_id': "iam_id"
  'password': "strong_password"
}

And to create dictionary, you need to name it (user), and give it key: value pairs ('user_id': "iam_id").

person = {
  'name': 'Anton',
  'shirt': 'Black',
  'laptop': 'Apple',
  'phone_number': '222-444-5555',
  'assets': 100,
  'debt': 50,
  'favorite_fruits': ['🍎', '🍐', '🍊'],
  'net_worth': lambda: person['assets'] - person['debt']
}

Dictionary methods

We created the dictionary but we don’t know how to access it. If we do pesron + . you will see the methods that dictionary data type has.

person.get('key')

This is one way to get the value of the key, but there is more simple way to achieve the same result.

person['name']

To use a value of the key, follow the structure above. dictionary_name comes first and ['key_name] comes after.

Methods .keys(), .values()

To get all the keys inside of the dictionary, we can use dictionary.keys() Same way, you can get all the values with dictionary.values().

Try run this code from your terminal.

def introducer():
  person = {
  'name': 'Anton',
  'shirt': 'Black',
  'laptop': 'Apple',
  'phone_number': '222-444-5555',
  'assets': 100,
  'debt': 50,
  'favorite_fruits': ['🍎', '🍐', '🍊'],
  'netWorth': lambda: person['assets'] - person['debt']
  }

  # print(f"πŸ‘‹ Hi My name is {person['name']}, \nπŸ‘¨β€πŸ’» the laptop I use to code is {person['laptop']}, \nπŸ‘• and I am wearing a {person['shirt']} shirt. \nπŸ’° My networth is {person['netWorth']()} USD. \n🍌 My favorite fruits are {person['favoriteFruits']}")

  # ❗ using a list() function to put values in the list!
  print(list(person.values()))
  print(person.keys())


introducer()

Function in dictionary

The dictionary can also contain other data types and functions too. For example, to calculate net_worth we have to make function.

def net_worth:
  return person['assets'] - person['debt']

But we cannot define function inside of the dictionary, so we need to use lambda here.

person = {
  'assets': 100,
  'debt': 50,
  'net_worth': lambda: person['assets'] - person['debt']
}

Exercise

Let’s create a function with dictionary

Try run this code in your terminal

def introducer():
  person = {
  'name': 'Anton',
  'shirt': 'Black',
  'laptop': 'Apple',
  'phone_number': '222-444-5555',
  'assets': 100,
  'debt': 50,
  'favorite_fruits': ['🍎', '🍐', '🍊'],
  'netWorth': lambda: person['assets'] - person['debt']
  }

  print(f"πŸ‘‹ Hi My name is {person['name']}, \nπŸ‘¨β€πŸ’» the laptop I use to code is {person['laptop']}, \nπŸ‘• and I am wearing a {person['shirt']} shirt. \nπŸ’° My networth is {person['netWorth']()} USD. \n🍌 My favorite fruits are {person['favorite_fruits']}")


introducer()

Now, break down this function by dictionary and print part.

The dictionary person has many key: value pair. It contains strings, numbers, function, and nested list.

The print is calling the value of dictionary. To call the value of dictionary, you need to use this syntax:

person['name']
# don't forget to put parenthesis to call function
print(f"πŸ’° My networth is {person['netWorth']()} USD.")

The print also has \n, but this time, we’ll not go into that. Just to inform, \n makes the row when you see the result from your terminal.

Alt text

Try run code from your terminal with \n and without \n. To select all the \n from your environment (VScode) ctrl + D

Editing the dictionary

What if user change thier password or email adress? Take a look our introducer again.

def introducer():
  person = {
  'name': 'Anton',
  'shirt': 'Black',
  'laptop': 'Apple',
  'phone_number': '222-444-5555',
  'assets': 100,
  'debt': 50,
  'favorite_fruits': ['🍎', '🍐', '🍊'],
  'netWorth': lambda: person['assets'] - person['debt']
  }

Let’s say we changed our laptop to Windows or you won lottery, so your assets is now 10000

Thankfully dictionary is mutable, so we can modify it. To modify the dictionary value, we need to access key.

person['laption'] = "Windows"
person['assets'] = 10000

It is easy to change the value. We access the key, and assign to another value with = sign`.

Try to add the code above to our introducer and see how the result changes

def introducer():
  person = {
  'name': 'Anton',
  'shirt': 'Black',
  'laptop': 'Apple',
  'phone_number': '222-444-5555',
  'assets': 100,
  'debt': 50,
  'favoriteFruits': ['🍎', '🍐', '🍊'],
  'netWorth': lambda: person['assets'] - person['debt']
  }

  person['laption'] = "Windows"
  person['assets'] = 10000

  print(f"πŸ‘‹ Hi My name is {person['name']}, \nπŸ‘¨β€πŸ’» the laptop I use to code is {person['laptop']}, \nπŸ‘• and I am wearing a {person['shirt']} shirt. \nπŸ’° My networth is {person['netWorth']()} USD. \n🍌 My favorite fruits are {person['favoriteFruits']}")
  # print(list(person.values()))
  # print(person.keys())


introducer()

Nested dictionary

Imagine the friend list from your app. We will do the similiar work here. We want to add friend in our person dictionary.

person = {
  'name': 'Anton',
  'shirt': 'Black',
  'laptop': 'Apple',
  'phone_number': '222-444-5555',
  'friend': {
    'name': 'Bruno',
    'shirt': 'Red',
    'laptop': 'Google',
    'phone_number': '666-777-8888',
    'favorite_fruits': ['πŸ₯­', 'πŸ₯₯'],
  },
  # ...
}

From the previous we learned dictionary can cotain many data types. And ditionary is also a data type, so we can put dictionary inside of dictionary. This is called nested dictionary.

To modify nested dictionary, we need to go in one more layer.

person['friend']['shirt'] = "white"
# also you can use .append
person['friend']['favorite_fruits'].append('πŸ₯')

Play with the code from your terminal and see the results.

Example πŸ‘‡

Alt text

Categories:

Updated:

Comments