Python Dictionary - Dict Object Type Tutorial with Examples - APPFICIAL

Publicado em: 08 Setembro 2021
no canal de: Appficial
1,242
13

In Python, a dictionary stores data as key-value pairs. Like a real dictionary book, when you look up a word for the definition, the word is the key, and the definition is the value. For example, if you look up Appficial, it should say something like “Best programming YouTube channel ever, and you should subscribe right now!”.

The object type for a dictionary is called a dict. Although it sounds like a funny word, you can easily create a dict object by using curly braces { } to surround the key-value pairs in your dictionary, with each key-value separated by a comma. You can create a dictionary of Detroit Pistons basketball players as follows:

pistons= {11:’Isaiah Thomas’, 4:’Joe Dumars’}
print(pistons)

You can create an empty dictionary by using empty curly braces.

Ex:
my_dict = { } # empty dict
big_dict = {1:’A’, 2:’B’, 3:’C’, 4:’D’, …. }

You would typically use a dictionary where key-value pair relationships exist. It might make more sense to store an associated relationship as a value to a key. For example, a person’s phone number can be a key, and an associative relationship as the value can include the persons name, address, date of birth, and so on.

Accessing dictionary entries

Dictionaries cannot be accessed by an index number, like you can with a list. Instead, access each value in a dictionary by passing the key inside square backets []. If no results are found, then you get a KeyError runtime error while your program is running, and it crashes.

Adding, modifying, and removing dictionary entries

A dictionary is mutable, so you can add new entries or update existing ones as needed. To add a new dictionary entry:

pistons[40] = ‘Billy Laimbeer’ #adds a new key-value pair, it it didn’t already exist in the dictionary
Pistons[10] = ‘Dennis Rodman’

To update an existing dictionary entry:

pistons[40] = ’Bill Laimbeer’ #updates the name for key number 40

To remove a dictionary entry:

del pistons[10] #deletes Dennis Rodman, since he got traded from the pistons


Subscribe to Appficial for more programming videos coming soon. Also, don't forget to click LIKE and comment on the video if it helped you out!


Nesta página do site você pode assistir ao vídeo on-line Python Dictionary - Dict Object Type Tutorial with Examples - APPFICIAL duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário Appficial 08 Setembro 2021, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 1,242 vezes e gostou 13 espectadores. Boa visualização!