Python Dictionary

In this Python tutorial, we will learn about Python Dictionary and we will also covers different examples related to Python Dictionary. And we will also covers these topics.

  • Python dictionary
  • Create a dictionary in Python
  • Adding element to a dictionary in Python
  • Accessing element of dictionary in Python
  • Removing element from a dictionary in Python

Python dictionary

In Python dictionary is used to store the values in key value pairs. The dictionary is also defines as a collection of ordered and changeable values. Dictionary are written with curly braces and separated by commas. The dictionary the value can be of any datatype and can be duplicated.

Example:

In the following example build a Python dictionary curly braces and separated by commas. Here we are written Pythontpoint in curly braces separated with commas.

Dic = {1: 'Python', 2: 'T', 3: 'Point'}
print(Dic)

Dic ={1: 'John', 2: 'Smith'}
print(Dic)

Output:

In the following output we can see that the dictionary with key value pair is printed on the screen by using print() function.

Python dictionary
Python dictionary

Github Link

Check this code in Repository from Github and you can also fork this code.

Github User Name: PythonT-Point

Create a dictionary in Python

A dictionary in python can be created by placed an elements in the curly brackets and separated by commas. It also carry the pair of values as a key values. The value in dictionary can be duplicate but can not be repeatable.

Examples:

In the following example we are creating a dictionary with integer and mixed keys and also creating an empty dictionary and creating a dictionary with dict() method.

  • Dic = {1: ‘Python’, 2: ‘T’, 3: ‘Point’} is used to create dictionary with integer keys.
  • print(“\n With the use of Integer Keys create a dictionary: “) is used to print dictionary with the use of integer.
  • Dic = {‘Name’: ‘Pythontpoint’, 1: [2, 4, 6, 8]} is used to create dictionary with mixed values.
  • Dic = {} is used to create an empty dictionary.
  • Dic = dict({1: ‘Python’, 2: ‘T’, 3: ‘Point’}) is used to create a dictionary with the help of dict() function.

# Create a Dictionary with Integer Keys
Dic = {1: 'Python', 2: 'T', 3: 'Point'}
print("\n With the use of Integer Keys create a dictionary: ")
print(Dic)
  
# Create a Dictionary with mixed keys
Dic = {'Name': 'Pythontpoint', 1: [2, 4, 6, 8]}
print("\n With the use of mixed Keys create dictionary: ")
print(Dic)

# Create an empty Dictionary
Dic = {}
print("Empty Dictionary: ")
print(Dic)
  
# Creating a Dictionary with dict() method
Dic = dict({1: 'Python', 2: 'T', 3: 'Point'})
print("\n With the use of dict() create dictionary: ")
print(Dic)

Output:

After running the above code we get the following output in which we can see that the dictionary is created with keys and dict() function.

Python Dictionary
Create a dictionary in python

So, with this we have learned how to create a dictionary in python and further we will learn how to create a dictionary in python.

Read: Python List

Adding element to a dictionary in Python

We can also add the elements by different ways. The value can be added to the dictionary along with key and we can also added a nested value to a dictionary and also update a dictionary by using update() method.

Example:

In the following example we are adding the element to a dictionary in python. Firstly we are creating the empty dictionary the adding the elements to the dictionary one at a time after that add the set of values to a single key then update the existing key value after that adding the nested key value to dictionary.

# Create an empty Dictionary
Dic = {}
print("Empty Dictionary: ")
print(Dic)
# Adding elements one at a time
Dic[1] = 'Python'
Dic[2] = 'Tpoint'

print("\nDictionary after adding 2 elements: ")
print(Dic)
  
# Add the set of values to a single Key
Dic['setofvalues'] = 2, 4, 6
print("\nDictionary after adding 3 elements: ")
print(Dic)
  
# Update the existing Key's Value
Dic[1] = 'MOSTWELCOME'
print("\nUpdate the key value: ")
print(Dic)
  
# Adding Nested Key value to Dictionary
Dic[4] = {'Nested': {'0': 'Live', '1': 'Life'}}
print("\nAdd a Nested Key: ")
print(Dic)

Output:

After running the above code we get the following output in which we can see that the elements are added to the dictionary in python.

Adding elements of dictionary in python
Adding elements of dictionary in python

Read: Python Literals

Accessing element of dictionary in Python

For accessing the elements of a dictionary suggested to as its key values and the key values can be paced inside the square brackets.

Examples:

In the following example we are accessing the elements of dictionary in python by simply uses the key values and these key values are placed inside the square brackets.

# Python program to accessing an element from a Dictionary
  
access_dic = {121: "John", 122: "Smith", 123: "Keller"}
# prints the acccessing element
print(access_dic[121])  
print(access_dic[123]) 

Output:

In this output, you can see that the values are accessing with the help of key value and printing on the screen.

Accessing element from dictionary in python
Accessing element from dictionary in python

Read: Python Strings

Removing element from a dictionary in Python

In Python we are using the del statement that remove an element from the dictionary. We are simply using del statement and the key value and those key value can be removed from the dictionary.

Example:

In the following example we are defining a dictionary and then print the original dictionary after that want to remove the element from the above dictionary by using del statement and then print the updated dictionary.

rm_studentid= {101: "Metairie", 102: "Joseph", 103: "Peggy"}

print("Initial Dictionary: ", rm_studentid)

del rm_studentid[102]

print("Updated Dictionary ", rm_studentid)

Output:

After running the above code we will get the following output in which we can see that the initial dictionary and the updated dictionary is printed on the screen.

Removing elements from a dictionary in python
Removing elements from a dictionary in python

So, in this tutorial, we have learned about the Python Dictionary and we have covered all these topics.

  • Python dictionary
  • Create a dictionary in Python
  • Adding element to a dictionary in Python
  • Accessing element of dictionary in Python
  • Removing element from a dictionary in Python

Do follow the following tutorials also:

106 thoughts on “Python Dictionary”

  1. It was impossible for me to leave your website without expressing my gratitude for the excellent knowledge you give your visitors. Without a doubt, I’ll be checking back frequently to see what updates you’ve made.

    Reply
  2. It is actually a nice and useful piece of information. I am happy that you simply shared this helpful information with us. Please keep us up to date like this. Thank you for sharing.

    Reply
  3. Hi my loved one! I wish to say that this article is amazing, great written and come with almost all important infos. I’d like to peer extra posts like this .

    Reply
  4. There are actually a whole lot of particulars like that to take into consideration. That is a nice level to convey up. I supply the thoughts above as common inspiration but clearly there are questions just like the one you deliver up where the most important thing can be working in sincere good faith. I don?t know if greatest practices have emerged round things like that, however I am positive that your job is clearly identified as a fair game. Each girls and boys feel the impact of just a second’s pleasure, for the remainder of their lives.

    Reply
  5. You really make it seem really easy along with your presentation but I to find this matter to be actually something that I feel I might by no means understand. It kind of feels too complex and very extensive for me. I’m looking ahead for your next post, I’ll try to get the hold of it!

    Reply
  6. Hello Neat post Theres an issue together with your site in internet explorer would check this IE still is the marketplace chief and a large element of other folks will leave out your magnificent writing due to this problem

    Reply
  7. I think this is one of the most vital info for me. And i am glad reading your article. But wanna remark on few general things, The site style is great, the articles is really great : D. Good job, cheers

    Reply
  8. My admiration for your creations is the same as your own opinion. The visual presentation is tasteful, while the written content is sophisticated. You’re skeptical, despite the fact that you are aware of it. I’m confident that you’ll be able to resolve this problem quickly and effectively.

    Reply
  9. I do love the manner in which you have framed this concern and it really does present me personally a lot of fodder for consideration. On the other hand, because of everything that I have seen, I really wish when the responses stack on that men and women continue to be on issue and not get started upon a soap box involving the news du jour. All the same, thank you for this superb piece and whilst I do not go along with the idea in totality, I value your perspective.

    Reply
  10. Your work has captivated me just as much as it has captivated you. The visual display is elegant, and the written content is impressive. Nevertheless, you seem concerned about the possibility of delivering something that may be viewed as dubious. I agree that you’ll be able to address this issue promptly.

    Reply
  11. Normalmente eu não leio artigos em blogs, mas gostaria de dizer que este artigo me forçou a tentar fazê-lo. Seu estilo de escrita me surpreendeu. Obrigado, ótima postagem

    Reply
  12. Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I’d prefer to use some with the content on my blog whether you don’t mind. Natually I’ll give you a link on your web blog. Thanks for sharing.

    Reply
  13. Techarp You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!

    Reply
  14. Simply Sseven You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!

    Reply
  15. Hi, I think your site might be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, fantastic blog!

    Reply
  16. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: сервисные центры по ремонту техники в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

    Reply
  17. anichin
    Hi, I do think this is a great web site. I stumbledupon it 😉 I am going to revisit once
    again since I book-marked it. Money and freedom is the greatest way to change, may you
    be rich and continue to guide other people.

    Reply
  18. Профессиональный сервисный центр по ремонту фототехники в Москве.
    Мы предлагаем: ремонт студийных вспышек
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
    Подробнее на сайте сервисного центра remont-vspyshek-realm.ru

    Reply
  19. Если кто ищет место, где можно выгодно купить раковины и ванны, рекомендую один интернет-магазин, который недавно открыл для себя. Они предлагают большой выбор сантехники и аксессуаров для ванной комнаты. Ассортимент включает различные модели, так что можно подобрать под любой стиль и размер помещения.

    Мне нужно было купить раковину , и они предложили несколько отличных вариантов. Цены приятно удивили, а качество товаров на высшем уровне. Также понравилось, что они предлагают услуги профессиональной установки. Доставка была быстрой, и всё прошло гладко. Теперь моя ванная комната выглядит просто великолепно!

    Reply
  20. <a href=”https://remont-kondicionerov-wik.ru”>ремонт кондиционеров на дому в москве</a>

    Reply
  21. tafsir mimpi 3d abjad tafsir mimpi 3d abjad tafsir mimpi 3d
    abjad tafsir mimpi 3d abjad (https://northernfortplayhouse.com/)
    Hello there! Quick question that’s entirely off
    topic. Do you know how to make your site mobile friendly? My blog looks weird when viewing from my iphone.
    I’m trying to find a template or plugin that might be
    able to fix this issue. If you have any recommendations, please share.
    Thanks!

    Reply
  22. Ищите лучшее онлайн казино? В этом топе представлены надежные платформы для игр на деньги и быстрым выводом на карту. С лицензией, официальные зеркала. Бонусы и фриспины. казино топ онлайн cacnjrrnxg … resol 1 онлайн казино топ-89085 | res4 онлайн казино топ-89085 | | demo5 онлайн казино топ-89085 | telegraph что такое онлайн казино онлайн казино топ-89085

    Reply
  23. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: сервис центры бытовой техники нижний новгород
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

    Reply
  24. demo slot pg demo slot pg demo slot pg demo
    slot pg
    When I initially commented I clicked the
    “Notify me when new comments are added” checkbox and now each
    time a comment is added I get three e-mails with the same comment.
    Is there any way you can remove people from that service?
    Thank you!

    Reply
  25. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры по ремонту техники в ростове на дону
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

    Reply
  26. win88 win88 win88
    I’m no longer certain the place you’re getting your info, but good topic.
    I must spend a while finding out much more or figuring out more.
    Thanks for wonderful information I used to be in search of this info for my mission.

    Reply
  27. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: ремонт крупногабаритной техники в воронеже
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

    Reply
  28. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: ремонт крупногабаритной техники в барнауле
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

    Reply
  29. bola88 bola88
    bola88
    Hi! This is kind of off topic but I need some help from an established blog.
    Is it hard to set up your own blog? I’m not very
    techincal but I can figure things out pretty fast.
    I’m thinking about making my own but I’m not sure where to begin.
    Do you have any ideas or suggestions? Many thanks

    Reply
  30. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

    Reply

Leave a Comment