Personal Blog
Programming

What is Dictionary in Python?

Python has some complicated data structures, such as: Lists, Tuples, Dictionaries and Sets

Dictionary is also called Associative Array. A dictionary consists of a collection of key-value pairs.

Definition:

d = {
    <key>: <value>,
    <key>: <value>,
      .
      .
      .
    <key>: <value>
}

Iteration Code:

dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
for key in dict:
     print(key)

Output:

color
fruit
pet

Code:

for item in dict.items():
     print(item)

Output:

('color', 'blue')
('fruit', 'apple')
('pet', 'dog')

Code:

for item in dict.items():
     print(item)
     print(type(item))

Output:

('color', 'blue')
<class 'tuple'>
('fruit', 'apple')
<class 'tuple'>
('pet', 'dog')
<class 'tuple'>

Code:

for key, value in dict.items():
     print(key, '->', value)

Output:

color -> blue
fruit -> apple
pet -> dog

References:

[1] https://realpython.com/iterate-through-dictionary-python/

Leave a Reply

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

Back to top