Python Dictionary

Python Dictionary

Table of Contents

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

KeysValues
personA human
runTo move quickly
shoeUsed to cover the human foot
marathon26-mile race
shoesPlural of shoe

Let’s see how to define a dictionary(dict)  in the python program.

Python Dictionary

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.

Python Dictionary

Example 2

Now let’s write the below in python program

Python Dictionary

Here is the program.

Python Dictionary

Get only keys or values

Python Dictionary

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

Python Dictionary

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.

Python Dictionary

len() function

If you want to find out how many key-value pairs exist in the dict then len() function is used.

Python Dictionary

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.

Python Dictionary

Copy the dict

NewGrocery = grocery.copy() will make a copy of the dictionary and store it in the new variable NewGrocery.

Python Dictionary

Dictionary Str(dict)

If you want your dictionary to be in the printable format then you can use str(dict) function

Python Dictionary

One Response

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class