oldoc63 / learningDS

Learning DS with Codecademy and Books
0 stars 0 forks source link

Make a Dictionary #350

Open oldoc63 opened 1 year ago

oldoc63 commented 1 year ago

The keys can be numbers as well. Values can be of any type. We can use a string, a number, a list, or even another dictionary as the value associated with a key.

oldoc63 commented 1 year ago

Invalid Keys

We can have a list or a dictionary as a value, but we cannot use these data types as keys, or we would get a TypeError.

oldoc63 commented 1 year ago

The word "unhashable" means that this list is an object that can be changed.

Dictionaries in Python rely on each key having a hash value, a specific identifier for the key. If the key can change, that hash value would not be reliable. So the keys must always be unchangeable, hashable data types, like numbers or strings.

oldoc63 commented 1 year ago

Empty Dictionary

A dictionary doesn't have to contain anything. Sometimes we need to create an empty dictionary when we plan to fill it later based on some other input.

oldoc63 commented 1 year ago

Add a Key

To add a single key: value pair

dictionary[key] = value
oldoc63 commented 1 year ago

Add Multiple Keys

If we wanted to add multiple key: value pairs to a dictionary at once, we can use the .update() method

oldoc63 commented 1 year ago

Overwrite Values

If we use a key that already has an entry in the dictionary our value assignment will overwrite the existing value attached to that key.