Chapter6 Flashcards
What is dictionary in python?
A dictionary in Python is a collection of key-value pairs.
what can be the key value?
Each key is connected to a value, and you can use a key to access the value associated with that key. A key’s value can be a number, a string, a list, or even another dictionary.In fact, you can use any object that you can create in Python as a value in a dictionary.
What kind of object should be use as values in python?
In fact, you can use any object that you can create in Python as a value in a dictionary.
How to create dictionary in python?
In Python, a dictionary is wrapped in braces, {}, with a series of key- value pairs inside the braces, as shown in the earlier example: alien_0 = {‘color’: ‘green’, ‘points’: 5}
how to access values in dictionary?
alien_0 = {‘color’: ‘green’}
print(alien_0[‘color’])
how to add New Key-Value Pairs?
a. Dictionaries are dynamic structures, and you can add new key-value pairs to a dictionary at any time
b. E.g alien_0[‘x_position’] = 0 alien_0[‘y_position’] = 25
how to start with an empty dictionary?
alien_0 = {} alien_0['color'] = 'green' alien_0['points'] = 5
Typically, you’ll use empty dictionaries when storing user-supplied data in a dictionary or when you write code that generates a large number of key-value pairs automatically.
How to Modifying Values in a Dictionary?
To modify a value in a dictionary, give the name of the dictionary with the key in square brackets and then the new value you want associated with that key.
alien_0[‘color’] = ‘yellow’
How to Remove Key-Value Pairs?
del alien_0[‘points’]
How to create dictonary over many lines?
a. You can also use a dictionary to store one kind of information about many objects favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
b. When you know you’ll need more than one line to de ne a dictionary, press enter after the opening brace. Then indent the next line one level (four spaces), and write the rst key-value pair, followed by a comma. From this point forward when you press enter, your text editor should automatically indent all subsequent key-value pairs to match the rst key-value pair.
It’s good practice to include a comma after the last key-value pair as well, so you’re ready to add a new key-value pair on the next line.
I am not sure if I finished , but checkd
??