Introduction
You must have seen a dictionary book in which there are words and explanations of them.
Python dictionary is just like a real-world dictionary in which the key-value pair is used. Let’s look at an example.
Example 1
Keys | Values |
person | A human |
run | To move quickly |
shoe | Used to cover the human foot |
marathon | 26-mile race |
shoes | Plural of shoe |
Let’s see how to define a dictionary(dict) in the python program.
First comes the name of the dictionary, here “dict” is used, then curly brackets in which keys and values are declared. Colon(:) is used to separate keys from their values as shown above.
After calling print() the following will be the output.
Example 2
Now let’s write the below in python program
Here is the program.
Get only keys or values
Properties of Dictionary Keys
There are two important points while using dictionary keys
- Duplication of keys is not allowed
- Keys must be immutable, and values can of any datatype.
Update
What if you want to buy eggs more? You need to update the value from 2.59 to 3.59 or you need to buy bread too. How you can do this? There is a built-in function for that purpose dict.update()
Let’s see in code how to increase the value of eggs as well as how to add bread.
Example
After the update, the final line shows that eggs values is 3.59 and an item is added “bread”:2.0
Delete Dictionary Elements
A single key-value pair and as well as whole dict can be deleted. Let’s see how.
len() function
If you want to find out how many key-value pairs exist in the dict then len() function is used.
As you can count there is a total of 6 key-value pairs.
Sorting dict keys and values
grocery and grocery.keys() gives us the on keys
grocery.values() gives us the values
sorted() function sort the output.
Copy the dict
NewGrocery = grocery.copy() will make a copy of the dictionary and store it in the new variable NewGrocery.
Dictionary Str(dict)
If you want your dictionary to be in the printable format then you can use str(dict) function
One Response