Back Python Tutorial for Beginners 5: Dictionaries - Working with Key-Value Pairs

5-10
Created By: Corey Schafer
Published At: 2017-05-17
Search Query: Python Arrays,Python Data Types,Python Delete Files,Python Dictionaries,Python Functions,Python Get Started,Python MongoDB Create Collection,Python MongoDB Find,Python MongoDB Get Started,Python MongoDB Get Started,Python MongoDB Insert,Python MongoDB Query,Python MongoDB Sort,Python MongoDB Sort,Python MongoDB Update,Python MySQL Delete,Python MySQL Insert,Python MySQL Select,Python MySQL Update,Python Numbers,Python Python MongoDB Delete,Python Read Files,Python Tutorial,Python Write Create Files
Tags: Python Python Dictionary Python dict Hashmap Associative Array Key-Value Pairs Python For Beginners Absolute Beginners Python for Absolute Beginners Python Basics Python Data Types Getting Started with Python Python 3.6 Python 36 Python 3 python dictionary tutorial python dictionaries in python python dictionary python tutorial python 3
In this Python Beginner Tutorial, we will begin learning about dictionaries. Dictionaries allow us to work with key-value pairs in Python. We will go over dictionary methods, how to add and remove values, and also how to loop through the key-value pairs. Let's get started.

The code from this video can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python-Dicts

Watch the full Python Beginner Series here:
https://www.youtube.com/playlist?list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7


βœ… Support My Channel Through Patreon:
https://www.patreon.com/coreyms

βœ… Become a Channel Member:
https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join

βœ… One-Time Contribution Through PayPal:
https://goo.gl/649HFY

βœ… Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot

βœ… Corey's Public Amazon Wishlist
http://a.co/inIyro1

βœ… Equipment I Use and Books I Recommend:
https://www.amazon.com/shop/coreyschafer

▢️ You Can Find Me On:
My Website - http://coreyms.com/
My Second Channel - https://www.youtube.com/c/coreymschafer
Facebook - https://www.facebook.com/CoreyMSchafer
Twitter - https://twitter.com/CoreyMSchafer
Instagram - https://www.instagram.com/coreymschafer/

#Python
logo Ask VidTutorAssistant
Comment
or
Question
Your name
Comments with generated responses
@chriswilliams7819
2017-05-19

why use student.update = "..." when you could just do student = "..."?

@coreyms

student.update allows you to only pass in the values you want to update. If you used "student = " then you would have to recreate all of the keys and values, even the ones that remained the same.

VidTutorAssistant (GPT-4)

Good question, @chriswilliams7819! The student.update line allows us to modify specific keys within our dictionary without affecting the others. If we used student = "...", we would overwrite the entire dictionary, losing any keys and values previously stored. The .update method is beneficial when you want to change some, but not all, key/value pairs, or if you want to add new keys. It's a more precise way of dealing with the data. That said, if you do want to replace the whole dictionary, student = "..." would be the correct approach. Hope this helps, and keep those Pythonic questions coming!


@ayushirajbhatt3520
2017-07-09

how can you update name of a key in a dictionary ? for example if I wanted to change the name from 'courses' to 'subjects' and still have all the values.

@coreyms

You could set 'subjects' to 'courses' and then just pop courses from the dict like so:
>>> d = {}
>>> d['courses'] = ['Math', 'History']
>>> d['subjects'] = d.get('courses')
>>> d
{'subjects': ['Math', 'History'], 'courses': ['Math', 'History']}
>>> d.pop('courses', None)
['Math', 'History']
>>> d
{'subjects': ['Math', 'History']}

VidTutorAssistant (GPT-4)

Hi @ayushirajbhatt3520, thanks for your comment! Updating the name of a key in a Python dictionary involves a two-step process. First, you need to add a new key with the desired name and assign the values from the existing key to this new key. Then, you can delete the existing key.

In your particular case, it would look something like this:

```
student['subjects'] = student['courses']
del student['courses']
```

This set of operations first creates a new key called 'subjects' and assigns the values from 'courses' to 'subjects'. Then, the 'del' keyword deletes the 'courses' key from the dictionary.

Remember, dictionary keys are unique, so if you try to add a key that already exists, it would override the current value with the new one.

I hope this answers your question. If you have any more doubts, feel free to ask. Happy Coding!


@kaustubh.sharma
2019-09-20

The day i'll get my first salary i'll surely contribute!
for now only i can say is Thank you so much!

@coreyms

Thanks!

VidTutorAssistant (GPT-4)

Thank you for your kind words and support, @kaustubh.sharma! I'm glad the content is useful to you. Your willingness to contribute in the future is greatly appreciated, but for now, your engagement and enthusiasm are more than enough. Keep learning and coding!


@petrisss2047
2017-11-21

Hello Corey, and thank you for your awesome tutorials. At 2:18 of this video did you said mutable or immutable data types? Because immutable sounds weird to me. It means data that can not be changed, but the strings and lists that we use here are muttable data right? Sorry for my noob questions but i just started learnig how to code! Thanks in advance! :)

@coreyms

The strings aren’t mutable. If when you change a string it actually changes the object it’s pointing to in the background. If you change a list or dictionary then it can actually modify that same object. I have a video on the difference between mutable and immutable on my channel if you want to search for it and get into more detail

VidTutorAssistant (GPT-4)

Hi @petrisss2047, thank you for the engaging question - no apologies needed for asking questions, we all start somewhere! At the time you're referring to, I actually said that keys in dictionaries can be any "immutable" data types. That's correct! In Python, only immutable data types can be used as keys to dictionaries. This is because keys in a dictionary need to be hashable, meaning they remain constant after they are created. That's why we often use strings or integers as keys which are indeed immutable.

On the other hand, lists, which you also mentioned, are mutable, meaning they can be changed even after their creation. That's why we cannot use a list as a dictionary key. I know these terms can be a bit confusing at times, but keep practicing and it'll become clearer! Hope this helps and keep up the good work!


@DdotTindall
2018-06-27

on the

FOR key, value IN student.ITEMS():

can someone explain how the for loop works?

because key and value are not defined until now and are arbitrary terms (could have chosen women, coke if i really wanted)

I know it then calls the PRINT function but I dont understand how this works.

Is it because the 'IN student' part tells the key, value to refer to student object? How are these stored in a 2x3 (column x row) matrix?

@coreyms

Hey there. Basically when you do the for-loop, it creates those variable names at that moment. So yes, you could have used any variable names you wish. And the reason you create two variables is because that is what the items method returns when iterated over. If you were to just loop over the dictionary itself, then it would loop over the keys, which is one value... so you would only create one variable at the beginning of that loop. Hope that makes sense.

VidTutorAssistant (GPT-4)

Hi @DdotTindall, great question! It seems like you have some confusion about how the for loop works in the context of dictionaries. Let's break it down.

The syntax `for key, value in student.items():` isn't reserves exclusively for 'key' and 'value'. As you correctly observed, they are arbitrary and could be any two variable names of your choosing.

The `key, value` part is called variable unpacking. Dictionaries store information in key-value pairs, and when we use `student.items()`, it returns these pairs as tuples. For instance, ('name', 'John') would be one of these tuples in our student dictionary. During each iteration of the for loop, one such tuple is 'unpacked' into two variables - key and value. Similarly, you could use `for women, coke in student.items():` and it would work similarly, setting 'women' to the key and 'coke' to the value.

As for your question on how these are stored in a 2x3 matrix, it's important to note that dictionaries in Python are not stored like matrices or tables, but rather as sequence of key-value pairs. You might want to think of it as a list of pairs, rather than a table with rows and columns.

I hope that clarifies things for you! Please don't hesitate to drop another comment if you have more questions. Happy coding!


@sazopro
2020-03-26

I'm studying Python on DataQuest and this channel is amazing to compliment the theory. Mos def will be donating soon!

@coreyms

Thanks!

VidTutorAssistant (GPT-4)

Hey @sazopro, I'm thrilled to hear that my channel is complementing your Python studies on DataQuest! It's rewarding to see that my explanations are helpful. Your support through donations is greatly appreciated but isn't necessary. Your learning is the most important thing to me. Remember, a simple like, comment, or a share with those who might benefit from the videos is also a great way to support the channel. Happy coding!


@harlynangeladesingano3123
2017-11-17

Hi, how can I store multiple dictionary in a dictionary like {{'name': 'Hey', 'age': 23}, {'name': 'Yow', 'age': 24}}. Thank youu

@coreyms

You could do a list of dictionaries like so:
[{'name': 'Hey', 'age': 23}, {'name': 'Yow', 'age': 24}]

Or you could create another level of keys like so:
{'person1': {'name': 'Hey', 'age': 23}, 'person2': {'name': 'Yow', 'age': 24}}

VidTutorAssistant (GPT-4)

Hi @harlynangeladesingano3123, great question! You're asking about nesting dictionaries, which is entirely possible in Python. Instead of directly storing dictionaries like {{'name': 'Hey', 'age': 23}, {'name': 'Yow', 'age': 24}}, you can store these dictionaries as values in another dictionary.

Here's an example:

```
people = {"person1": {'name': 'Hey', 'age': 23}, "person2": {'name': 'Yow', 'age': 24}}
```

In this case, `"person1"` and `"person2"` are the keys to the outer dictionary, and their respective values are the inner dictionaries. To access the 'name' entry for 'person1', you would use:

```
print(people["person1"]["name"])
```

This would output 'Hey'. Remember, dictionaries are a powerful tool in Python, and understanding the full scope of their capabilities, such as nesting, can really take your code to the next level. I hope this helps, and if you have any other questions, do not hesitate to ask! Happy coding!