Dictionary In Python – See How To Make A Dictionary Of Your Own

Let’s say you started a retail shop🏬.

You had a grand opening ceremony🎉. And, you are super excited 🤩 to grow your business📊.

Then, you decided to use lists in python to remember where to place what.

But, a problem arises, instead of making your work easy lists are creating problems 🤦‍♀️ for you. Don’t worry a python dictionary will help you.

Hello Pythonistas, welcome back. In this post, we are gonna take a look at dictionaries 📚 in python.

Previous post’s challenge’s solution

Before we get started here’s the solution to the previous post’s challenge:

Madlib_logo ='''
            , ; ,     
        .'         '.
       /   ()   ()   \\
      ;               ;
      ; :.  MADLIB .; ;
       \\'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'
'''
print(Madlib_logo)
#step1: Store story in a variable.
story = '''A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"'''

#step2: Input variables.
name = input("Enter a name:- ")
skill = input("Enter a skill:- ")
object_ = input("Enter any object:- ")
verb1 = input("Enter a verb:- ")
verb2 = input("Enter another verb:- ")
verb3 = input("Enter a verb again:- ")
adjective = input("Enter an adjective:- ")

#step3: Store the variables in a list
blanks = [name, skill, object_, verb1, verb2, verb3, adjective]

#step4: Merge variable in story using an f-string
changed_story = f'''A {blanks[6]} boy named {blanks[0]} had just passed his {blanks[1]} test
and asked his Dad if he could start using the family {blanks[2]}. The Dad
said he'd make a {blanks[3]} with {blanks[0]}, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the {blanks[2]}". {blanks[0]} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "{blanks[0]}, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
{blanks[0]} said, "You know, Dad, I've been {blanks[4]} about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all {blanks[5]} everywhere they went?"'''

#step5: print both the stories
print(f"\n\n-----------Original Story-----------\n{story}\n\n-----------Madlib Story-----------\n{changed_story}")

Output:-

            , ; ,     
        .'         '.
       /   ()   ()   \
      ;               ;
      ; :.  MADLIB .; ;
       \'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'

Enter a name:- someone
Enter a skill:- programming
Enter any object:- laptop
Enter a verb:- typing
Enter another verb:- searching
Enter a verb again:- creating
Enter an adjective:- fast


-----------Original Story-----------
A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"

-----------Madlib Story-----------
A fast boy named someone had just passed his programming test
and asked his Dad if he could start using the family laptop. The Dad
said he'd make a typing with someone, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the laptop". someone thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "someone, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
someone said, "You know, Dad, I've been searching about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all creating everywhere they went?"

I think the solution is self-explanatory. But, feel free to comment if you don’t understand anything. Remember,

“The man who asks a question is a fool for a minute, the man who does not ask is a fool for life.”

― Confucius

Now, let’s take a deeper look at dictionaries in python.

What is a dictionary?

What comes to your mind when I say dictionary? A book with all the words and their meaning.

Well, a dictionary which is a data type in python is quite similar to this one.

It is a bunch of “key-value” pairs separated by commas "," and enclosed in curly brackets {}.

Here’s an example of one:-

where_is_what = {"apple": "top row of shelf",
"banana": "bottom row of the shelf",
"spinach": "middle row of the shelf"}
print(where_is_what)
print(type(where_is_what))

Output:-

{'apple': 'top row of shelf', 'banana': 'bottom row of the shelf', 'spinach': 'middle row of the shelf'}
<class 'dict'>

NOTE:- the key-value pair is separated by a ":"

Here apple🍎, banana🍌, and spinach 🥦 are keys using which you can find their values. In our case their location. We will see how you can use keys to get their values further in the post.

Some restrictions on keys

The keys in dictionaries must be immutable. Meaning you cannot use a list as a dict’s key. Let’s try to use it and see what happens.

dict1 = {[1, 2, 3]: 1,
[4, 5, 6]: 2,
[7, 8, 9]: 3}
print(dict1)

Output:-

Traceback (most recent call last):
File "c:UsersDesktoppython-hub.compython_dictionary.py", line 1, in
dict1 = {[1, 2, 3]: 1, [4, 5, 6]: 2, [7, 8, 9]: 3}
TypeError: unhashable type: 'list'

Now you must be wondering🤔 why is it saying list unhashable it should say immutable. What is the difference between immutable and unhashable? Take a deep breath and don’t worry😇. For now, you just have to take them both as the same. Later on, when you’ll get into advanced python you’ll know✔ the difference.

Let’s move on to see ways to create a dictionary.

Two ways to create a dictionary

Using curly brackets

This is the way we just used. You can create both an empty dictionary and a dictionary with data. See the examples below:-

empty = {}
print(empty)
where_is_what = {"apple": "top row of shelf",
"banana": "bottom row of the shelf",
"spinach": "middle row of the shelf"}
print(where_is_what)

Output:-

{}
{'apple': 'top row of shelf', 'banana': 'bottom row of the shelf', 'spinach': 'middle row of the shelf'}

Wondering why to create an empty dictionary?

Well, simple enough say you just don’t know for now what you want to store where you want to store in your store. (Tounge 😜 twister isn’t it?)

Using the dict() function

Like we had functions for all the other data types we saw by now strings, integers, floats, lists, etc. dictionaries too have a function. Using the dict() function you can easily create a dictionary.

Example:-

empty1 = dict()
print(empty1)
where_is_what = dict(apple="top row of shelf", banana= "bottom row of the shelf", spinach= "middle row of the shelf")
print(where_is_what)

Output:-

{}
{'apple': 'top row of shelf', 'banana': 'bottom row of the shelf', 'spinach': 'middle row of the shelf'}

There is a third possible way to do this that is dictionary comprehension. But, for that, you’ll need to know loops so as of now just understand these two.

Now that you have created where_is_what time to access values using keys🗝.

Accessing values of a dictionary

Let’s say your friend comes to your shop to buy an apple🍎. Then you search in your dict where’s my apple this way:-

where_is_what = {"apple": "top row of shelf",
"banana": "bottom row of the shelf",
"spinach": "middle row of the shelf"}
print(where_is_what['apple'])

Output:-

top row of shelf

You can make results look even more clear using an f-string:

print(f"Where's my apple? It is in the:- {where_is_what['apple']}")

Output:-

Where's my apple? It is in the:- top row of shelf

Similarly, you can easily access any other item’s location.

It’s been a month and you are making great progress in the store and decided to expand your product line and make a few changes. Let’s do them.

Changing already created dictionary

Before we start making changes in our where_is_what for our shop’s expansion. Remember this, only values in a python dictionary are mutable not keys. Because dictionaries are not like lists where you stored data in order. The only way to access values is through keys that’s why they are immutable.

In case I forgot to mention dictionary is an unordered sequence.✨

Adding new elements

Let’s say along with apple🍎, banana🍌 and spinach🥦 now you are going to keep pineapples🍍, kiwi🥝, and oranges🍊 too in your store which means you need to add their location here in the dictionary where_is_what. This is how:-

where_is_what = {"apple": "top row of shelf",
"banana": "bottom row of the shelf",
"spinach": "middle row of the shelf"}
print(f"Before:- {where_is_what}\n")
where_is_what["pineapples"]="top left corner"
where_is_what["kiwi"]="top right corner"
where_is_what["oranges"]="bottom left corner"
print(f"After:- {where_is_what}")

Output:-

Before:- {'apple': 'top row of shelf', 'banana': 'bottom row of the shelf', 'spinach': 'middle row of the shelf'}
After:- {'apple': 'top row of shelf', 'banana': 'bottom row of the shelf', 'spinach': 'middle row of the shelf', 'pineapples': 'top left corner', 'kiwi': 'top right corner', 'oranges': 'bottom left corner'}

Updating/changing elements

Now you thought that you must keep spinach 🥦 in the top row. Apples🍎, pineapples🍍, and bananas🍌 should be in the second row. And kiwi 🥝and oranges🍊 in the bottom row. This means you need to update the already existing data. Here’s how you will do it:-

print(f"Before:- {where_is_what}\n")
where_is_what["spinach"]="top row"
where_is_what["apple"]="middle row left corner"
where_is_what["pineapples"]="middle row center"
where_is_what["banana"]= "middle row right corner"
where_is_what["kiwi"]="bottom row left corner"
where_is_what["oranges"]="bottom row right corner"
print(f"After:- {where_is_what}")

Output:-

Before:- {'apple': 'top row of shelf', 'banana': 'bottom row of the shelf', 'spinach': 'middle row of the shelf', 'pineapples': 'top left corner', 'kiwi': 'top right corner', 'oranges': 'bottom left corner'}
After:- {'apple': 'middle row left corner', 'banana': 'middle row right corner', 'spinach': 'top row', 'pineapples': 'middle row center', 'kiwi': 'bottom row left corner', 'oranges': 'bottom row right corner'}

Deleting elements

You just realized that kiwi🥝 and oranges🍊 don’t have a good enough demand and decided to remove them from your shop. This is how you will record these changes in your where_is_what:-

print(f"Before:- {where_is_what}\n")
del where_is_what["kiwi"]
del where_is_what["oranges"]
print(f"After:- {where_is_what}")

Output:-

Before:- {'apple': 'middle row left corner', 'banana': 'middle row right corner', 'spinach': 'top row', 'pineapples': 'middle row center', 'kiwi': 'bottom row left corner', 'oranges': 'bottom row right corner'}
After:- {'apple': 'middle row left corner', 'banana': 'middle row right corner', 'spinach': 'top row', 'pineapples': 'middle row center'}

Time ⌚ to take a look at some amazing functions/methods on dictionaries.

Dictionary Methods/functions

keys()

Now after the expansion of your shop, an income 💵 tax officer asks for a list of the items you sell in your shop. This is how you’ll give him the list:-

print(f" The list of items we sell:- {where_is_what.keys()}")
Output
The list of items we sell:- dict_keys(['apple', 'banana', 'spinach', 'pineapples'])

values()

This function is just like the above one but instead of keys, it provides a list of values. Example:-

print(f" All the locations:- {where_is_what.values()}")
Output
All the locations:- dict_values(['middle row left corner', 'middle row right corner', 'top row', 'middle row center'])

items()

This provides a tuple for all the key-value pairs. Example:-

print(where_is_what.items())
Output
dict_items([('apple', 'middle row left corner'), ('banana', 'middle row right corner'), ('spinach', 'top row'), ('pineapples', 'middle row center')])

If you are interested in knowing more dictionary functions then read the official documentation.

Conclusion

In this post, you opened a shop 🏢🏬 and were confused 🤔about how to store the locations of items🥦🍍🍎🍌🍊🥝 you sell in your store using python dictionaries.

Then, you created a dictionary named where_is_what.

After that, you used it and grew your business.

Finally, you expanded your business due to exponential growth.

And also learned some awesome functions/methods that will make use of where_is_what even better.

Challenge🧗‍♀️

Ok, so your challenge is to create a dictionary📚 that stores the prices🏷 of products that you sell, revenue💵 generated from each of your products, and finally profit💰 earned on each of your products. This might prove to be a simple exercise for you because you’ve solved a lot of difficult challenges by now.

Hint:- You would need to use lists and dictionaries together.

Go fast. I am waiting. Comment your answers below.

This was it for the post. Comment below suggestions if there and tell me whether you liked it or not. Do consider sharing this with your friends.

See you in the next post till then have a great time.😊

Leave a Reply

This Post Has 10 Comments

  1. Twicsy

    You actually make it seem so easy with your presentation but I find this matter to be really something that I think I would
    never understand. It seems too complicated and extremely broad for me.

    I am looking forward for your next post, I will try to get the hang of it!

  2. Maitry

    Thanks a lot, Twicsy please stay tuned and comment any doubts you have with Python. I’ll definitely try my best to help you.

  3. Maitry

    Thanks a lot. Happy to know you liked it. Stay tuned to get even more on python programming. And it’s been a few months since I started blogging.

  4. Woah! I’m really enjoying the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance”
    between usability and visual appearance. I must say that you’ve done a amazing job with this.
    In addition, the blog loads extremely quick for me on Chrome.
    Exceptional Blog!

  5. Maitry

    Thanks a lot, it is great to know you like it and it helps you. Stay tuned for more

  6. Maitry

    Thanks a lot. Glad to hear it helps.

  7. Isabelle

    I have been browsing online more than three hours lately,
    but I never found any fascinating article like yours. It’s lovely worth sufficient
    for me. In my view, if all website owners and bloggers made good content material as you probably did,
    the web will likely be a lot more useful than ever before.

  8. Maitry

    Thank You!