Search code snippets, questions, articles...

Loop through a dictionary in Python

To access the items of a dictionary in python we can use python For loop. We get the key of dictionary in each iteration.
car = {
    'name': 'Nexon',
    'brand': 'TATA',
    'type': 'EV',
    'vendor': 'Ztx'
}

for key in car:
    print(key, end=": ")
    print(car[key])

# name Nexon
# brand TATA
# type EV
# vendor Ztx
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

A dictionary is a key-value pair data assignment in python. If you have used a dictionary in python and you want to use the values of dictionary keys in your code then you can use For loop to access them.

items = {
  'key_1': 'value_1',
  'key_2': 'value_2',
  'key_3': 'value_3'
}

for key in items:
  print(key)

# -> key_1
# -> key_2
# -> key_3
We are printing each key that exists inside a dictionary using For loop. In each iteration, we get the key and use it inside the print function.
items = {
  'key_1': 'value_1',
  'key_2': 'value_2',
  'key_3': 'value_3'
}

for key in items.values():
  print(key)

# -> value_1
# -> value_2
# -> value_3
We are using the dictionary.values() function that will return all the values from the dictionary. We are applying For loop on these values and printing them one by one.
companies = {
  'microsoft': 'BillGates',
  'apple': 'Steve Jobs',
  'resla': 'Elon Musk',
  'google': 'Larry Page'
}

for key, value in companies.items():
  print(key, ': ', value)

# microsoft :  BillGates
# apple :  Steve Jobs
# resla :  Elon Musk
# google :  Larry Page
We can get both key and value inside for loop in each iteration. We will be applying For loop on dictionary.items()> to access key and value.
Was this helpful?
0 Comments