Introduction

Dictionaries are used to store values in key: value pairs,

1. A simple dictionary,

simple_dict = {
  "age": 29,
  "country": "Ke",
  "gender": "Female"
}

Print the dictionary:


print(simple_dict)
# outputs
{'age': 29, 'country': 'Ke', 'gender': 'Female'}

2. Access the dictionary items

Print “age” value:

print(simple_dict["age"])
# outputs:
29

Duplicate keys are not allowed.

simple_dict = {
  "age": 29,
  "age": 30,
  "country": "Ke",
  "gender": "Female"
}

print(simple_dict)
# outputs:
{'age': 30, 'country': 'Ke', 'gender': 'Female'}

3. Get the length of the Dictionary

we use len function to get the size(number of entries):

print(len(simple_dict))
# outputs
3

4. How to iterate/loop through the keys and values

we use a for-in loop as follows:

for key in simple_dict:
  print(key, '->', simple_dict[key])

outputs:
age -> 30
country -> Ke
gender -> Female

5. How to merge 2 or more dictionaries

To merge 2 or more dictionaries:

  1. Using the update method, we merge the dictionary with other items and gets rid of duplicate items:
simple_dict = {
  "age": 29,
  "age": 30,
  "country": "Ke",
  "gender": "Female"
}

simple_dict2 = {
  "city": "Nairobi",
  "hobbies": ["Hiking", "gaming"]
}

final = simple_dict.copy()
final.update(simple_dict2)

print(final)
# {'age': 30, 'country': 'Ke', 'gender': 'Female', 'city': 'Nairobi', 'hobbies': ['Hiking', 'gaming']}
  1. Using the merge operator (|) This was introduced in Python 3.9

The previous example can be done in a oneliner using the unpack operator(**)

final = simple_dict | simple_dict2
print(final)
# {'age': 30, 'country': 'Ke', 'gender': 'Female', 'city': 'Nairobi', 'hobbies': ['Hiking', 'gaming']}

  1. Using the unpack operator (**)

The above can be done in a oneliner using the unpack operator(**)

final = {**simple_dict, **simple_dict2}

print(final)
# {'age': 30, 'country': 'Ke', 'gender': 'Female', 'city': 'Nairobi', 'hobbies': ['Hiking', 'gaming']}

For best practices when working with Dictionaries, check out this comprehensive guide


Found this article helpful? You may follow me on Twitter where I tweet about interesting topics on software development.