Iterate over a dictionary in Python

PythonServer Side ProgrammingProgramming

In this article, we will learn about iteration/traversal of a dictionary in Python 3.x. Or earlier.

A dictionary is an unordered sequence of key-value pairs. Indices can be of any immutable type and are called keys. This is also specified within curly braces.

Method 1 − Using iterables directly

Example

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}

# Iterate over the string
for value in dict_inp:
   print(value, end='')

Output

trason

Method 2 − Using iterables for values of the dictionary

Example

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}

# Iterate over the string
for value in dict_inp.values():
   print(value, end='')

Output

oilpit

Method 3 − Using keys as an index

Example

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}

# Iterate over the string
for value in dict_inp:
   print(dict_inp[value], end='')

Output

oilpit

Method 4 − Using keys and values of the dictionary

Example

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}

# Iterate over the string
for value,char in dict_inp.items():
   print(value,":",char, end=" ")

Output

t : o r : i a : l s : p o : i n : t

Conclusion

In this article, we learned about iteration/traversal over a dictionary in Python.

raja
Published on 07-Aug-2019 07:55:48
Advertisements