Dictionaries in Python _ Databytes _ Python Basics Tutorial

Creating a Dictionary in Python

=====================================

Python dictionaries are collections of key-value pairs. A dictionary's keys can be any type of data, including numbers and text, while its values can also be any type of data.

Creating a Dictionary

----------------------

To create a dictionary, we use the `dict` keyword followed by an equals sign and a set of curly brackets containing key-value pairs. For example:

```python

fruits = {"apple": "red", "banana": "yellow"}

```

In this example, we have created a dictionary called `fruits` with two key-value pairs: `"apple"` mapped to `"red"` and `"banana"` mapped to `"yellow"`.

Accessing Dictionary Keys and Values

---------------------------------------

Python dictionaries allow us to access their keys and values using square brackets. To get the value of a specific key, we simply use that key in square brackets:

```python

print(fruits["apple"]) # Output: red

# Using the get method:

print(fruits.get("banana")) # Output: yellow

```

The `get` method behaves similarly to accessing a key using square brackets but provides an optional default value if the key is not found in the dictionary.

Editing Dictionary Keys and Values

--------------------------------------

To edit or add new keys-value pairs to an existing dictionary, we use the same syntax as when creating a dictionary:

```python

fruits["orange"] = "orange"

fruits["melon"] = "green"

print(fruits) # Output: {"apple": "red", "banana": "yellow", "orange": "orange", "melon": "green"}

```

In this example, we have added two new key-value pairs to the `fruits` dictionary.

Retrieving Dictionary Keys and Values

-----------------------------------------

Python dictionaries also provide methods to retrieve their keys and values. To get all keys in a dictionary, we use the `.keys()` method:

```python

print(fruits.keys()) # Output: dict_keys(["apple", "banana", "orange", "melon"])

```

To get all values in a dictionary, we use the `.values()` method:

```python

print(fruits.values()) # Output: dict_values(["red", "yellow", "orange", "green"])

```

To get both keys and values as a list of tuples, we use the `.items()` method:

```python

print(fruits.items()) # Output: dict_items([("apple", "red"), ("banana", "yellow"), ("orange", "orange"), ("melon", "green")])

```

Checking if a Key Exists in a Dictionary

---------------------------------------------

To check if a specific key exists in a dictionary, we use the `in` keyword:

```python

print("apple" in fruits) # Output: True

print("carrot" in fruits) # Output: False

```

Adding New Key-Value Pairs to a Dictionary

---------------------------------------------

To add new key-value pairs to an existing dictionary, we can use the `.update()` method or simply add the new key-value pair using square brackets:

```python

fruits.update({"pear": "brown", "grape": "red"})

print(fruits) # Output: {"apple": "red", "banana": "yellow", "orange": "orange", "melon": "green", "pear": "brown", "grape": "red"}

```

Alternatively, we can add new key-value pairs using square brackets:

```python

fruits["pear"] = "brown"

fruits["grape"] = "red"

print(fruits) # Output: {"apple": "red", "banana": "yellow", "orange": "orange", "melon": "green", "pear": "brown", "grape": "red"}

```

Removing Key-Value Pairs from a Dictionary

---------------------------------------------

To remove key-value pairs from an existing dictionary, we can use the `.pop()` method or the `del` keyword:

```python

fruits.pop("melon")

print(fruits) # Output: {"apple": "red", "banana": "yellow", "orange": "orange", "grape": "red"}

del fruits["orange"]

print(fruits) # Output: {"apple": "red", "banana": "yellow", "grape": "red"}

```

Alternatively, we can use the `clear()` method to empty a dictionary:

```python

fruits.clear()

print(fruits) # Output: {}

```

"WEBVTTKind: captionsLanguage: enhello everyone this is justin from datacamp and today we'll be covering python dictionaries we're going to go over creating a dictionary accessing the values in a dictionary and editing a dictionary we're going to be using data camp workspace which is an online id which you can use to write code analyze data collaboratively and share your insights if you'd like to follow along in this exact workspace you can follow the link in the description below and register for a free account so to start python dictionaries are a collection of key value pairs every value in the dictionary is assigned to a unique key to create a dictionary we're going to name one fruits and then we initialize it with curly brackets and then we start with our first key which we'll call apple then to separate the key and the value you use a colon and then the value that you want to specify so we're going to call this red add another key value pair inside of the brackets we're going to add a comma and then another fruit so we'll call this banana and again we use the colon to separate the key and the value and then we're going to give this the color yellow and then we're going to use the print function to print our dictionary to confirm it is worked and sure enough we see the output of our dictionary now dictionary keys can be a number of different data types including numbers and text python dictionary values can be any type of data so we're going to test that out we're going to create another dictionary called apple and we're going to give it a calories key and we'll use a number for this so we'll say 52 calories we're going to give it a tasty key and we're going to pass in a true false value or a boolean so i'm going to call that true and then we're going to add one final key value pair we're going to say types and we'll pass it pass in a list this time so fuji and gala and if we print this dictionary again we see that all three different types of data are stored as values in our python dictionary now you can check the length of your dictionary using the len function so let's quickly check the length of our apple dictionary and sure enough we were shown the three key values pairs that we specified now to access the values and keys in a dictionary there are a number of ways you can do it one is just just use square brackets so here we're going to use our fruits dictionary and we're going to get the color of apples now we're going to close this in a print function so we can print this but we're also going to try using the get method which behaves in much the same way so we'll specify the name of our dictionary but this time we'll call the get method and inside we'll pass the name of the key that we want and you'll see that both return red so there's two different ways of retrieving the value of a specific key in a dictionary if you want to view all of the individual keys in a in order of insertion of a dictionary you can use the dot keys method so here we would do fruits dot keys and if we run this enclosed in a print we will see all of the keys apple and banana if we want to get all of the values we can do the same thing so fruits dot values instead of keys and finally if you want to retrieve every key value pair we can use the dot items method so fruit stop items if we run this we get every key value pair that we specified apple red banana yellow now you can check whether an individual key is inside of a dictionary using the in keyword so let's start by using one that we know is not in there so let's say carrot in fruits and if we run this we see false but if we use a key that we know is in there apple we get true now once you create a dictionary it's not fixed you can add an edit to a dictionary so let's add a new key and we can do that using the square brackets that we used earlier so let's use fruits but this time add in a grape and add in a red grape and if we view our dictionary we'll see that we now have a new key value pair of red a great red now what this will do is it will add a new key value pair if this key doesn't exist if the key does exist it will update it to the new value so let's say we actually want to change that to being green we do this again we see that we've updated the key value pair so that grape is now green alternatively you can use the update method um to add one or more keys to a dictionary so let's try that now as an argument you um use curly braces as you would when you're creating a dictionary and let's add in um cool new entries so orange orange uh and now let's also add a melon and we'll call this green now if we look at our dictionary we'll see that we have these new entries of orange and melon let's say you want to actually remove some items from a dictionary well the first thing you can do is you can use the pop method so let's use fruits dot pop and we're going to specify the key that we want to remove we want to remove melon and then let's print fruits and sure enough we can see that we've removed that entry melon you can also use the del keyword to delete a key value pair by the key so we can use dell and then uh the um square brackets that we used before so let's get rid of orange and now if we print boots let's see we also no longer have orange finally you can use the clear method to empty a dictionary entirely so let's use fruit stock clear and if we print fruits now we'll see that we've emptied it entirely and that concludes this tutorial i hope you found it helpful we covered creating a dictionary accessing the values in a dictionary and editing a dictionary if you found this helpful be sure to like and subscribe and follow for future content and be sure to check out the resources below thanks again youhello everyone this is justin from datacamp and today we'll be covering python dictionaries we're going to go over creating a dictionary accessing the values in a dictionary and editing a dictionary we're going to be using data camp workspace which is an online id which you can use to write code analyze data collaboratively and share your insights if you'd like to follow along in this exact workspace you can follow the link in the description below and register for a free account so to start python dictionaries are a collection of key value pairs every value in the dictionary is assigned to a unique key to create a dictionary we're going to name one fruits and then we initialize it with curly brackets and then we start with our first key which we'll call apple then to separate the key and the value you use a colon and then the value that you want to specify so we're going to call this red add another key value pair inside of the brackets we're going to add a comma and then another fruit so we'll call this banana and again we use the colon to separate the key and the value and then we're going to give this the color yellow and then we're going to use the print function to print our dictionary to confirm it is worked and sure enough we see the output of our dictionary now dictionary keys can be a number of different data types including numbers and text python dictionary values can be any type of data so we're going to test that out we're going to create another dictionary called apple and we're going to give it a calories key and we'll use a number for this so we'll say 52 calories we're going to give it a tasty key and we're going to pass in a true false value or a boolean so i'm going to call that true and then we're going to add one final key value pair we're going to say types and we'll pass it pass in a list this time so fuji and gala and if we print this dictionary again we see that all three different types of data are stored as values in our python dictionary now you can check the length of your dictionary using the len function so let's quickly check the length of our apple dictionary and sure enough we were shown the three key values pairs that we specified now to access the values and keys in a dictionary there are a number of ways you can do it one is just just use square brackets so here we're going to use our fruits dictionary and we're going to get the color of apples now we're going to close this in a print function so we can print this but we're also going to try using the get method which behaves in much the same way so we'll specify the name of our dictionary but this time we'll call the get method and inside we'll pass the name of the key that we want and you'll see that both return red so there's two different ways of retrieving the value of a specific key in a dictionary if you want to view all of the individual keys in a in order of insertion of a dictionary you can use the dot keys method so here we would do fruits dot keys and if we run this enclosed in a print we will see all of the keys apple and banana if we want to get all of the values we can do the same thing so fruits dot values instead of keys and finally if you want to retrieve every key value pair we can use the dot items method so fruit stop items if we run this we get every key value pair that we specified apple red banana yellow now you can check whether an individual key is inside of a dictionary using the in keyword so let's start by using one that we know is not in there so let's say carrot in fruits and if we run this we see false but if we use a key that we know is in there apple we get true now once you create a dictionary it's not fixed you can add an edit to a dictionary so let's add a new key and we can do that using the square brackets that we used earlier so let's use fruits but this time add in a grape and add in a red grape and if we view our dictionary we'll see that we now have a new key value pair of red a great red now what this will do is it will add a new key value pair if this key doesn't exist if the key does exist it will update it to the new value so let's say we actually want to change that to being green we do this again we see that we've updated the key value pair so that grape is now green alternatively you can use the update method um to add one or more keys to a dictionary so let's try that now as an argument you um use curly braces as you would when you're creating a dictionary and let's add in um cool new entries so orange orange uh and now let's also add a melon and we'll call this green now if we look at our dictionary we'll see that we have these new entries of orange and melon let's say you want to actually remove some items from a dictionary well the first thing you can do is you can use the pop method so let's use fruits dot pop and we're going to specify the key that we want to remove we want to remove melon and then let's print fruits and sure enough we can see that we've removed that entry melon you can also use the del keyword to delete a key value pair by the key so we can use dell and then uh the um square brackets that we used before so let's get rid of orange and now if we print boots let's see we also no longer have orange finally you can use the clear method to empty a dictionary entirely so let's use fruit stock clear and if we print fruits now we'll see that we've emptied it entirely and that concludes this tutorial i hope you found it helpful we covered creating a dictionary accessing the values in a dictionary and editing a dictionary if you found this helpful be sure to like and subscribe and follow for future content and be sure to check out the resources below thanks again you\n"