![]() ![]() If I try to access the zeroeth item, I'm going to get an error saying I expect to key and that key does not exist. Now, dictionaries, like sets do not have an order in my dict, there is no zeroeth item or first item. Because when I want to retrieve this item from my dictionary, I'll be doing it by its key. So you can say my_numbers are a dictionary and say, the key is one and the value is this list. Dictionary values do not have that same restriction. ![]() Now, dictionary keys need to be immutable. And that will show me that it is a dictionary. I can go ahead and assign this to a variable and then check its type. And that has now given me a dictionary with two key value pairs in it. So the key is on the left hand side of the colon, the value is on the right hand side of the colon, separated with commas. If I wanted to create dictionaries with items in them, I would now have to define keys and values. If I wanted to create an empty dictionary, how do I do that? So if sets had curly braces, dictionaries have curly braces and colons and that colon is how you differentiate between the key and the value. But let's go through some examples of what dictionaries in Python look like. I have a dictionary cheat sheet here for you. Tuples are immutable, so we can use them as a dictionary key. Can we have a tuple as a dictionary key? Yes. We cannot have mutable data types as dictionary keys. So a list is mutable dictionary keys can only be immutable. If I ask that question correctly, I would get a better answer. And that's because the hash of the key is compared with the hash of the keys in the dictionary, don't have to look through it each item in that dictionary and say, are are you the item, are you the item, are you the item that I'm looking for? So can I have a list as a dictionary and a key, or I'm sorry, a list as a key in the dictionary? Dictionaries allow fast item lookup and fast membership testing you can quickly say, given a key is this key in my dictionary or not. Why? Because dictionary keys need to be hashable. Dictionaries themselves aren't mutable, but just like sets, dictionary keys is can only be immutable. Dictionaries are a data type that allow us to store key and value pairs.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |