Friday, November 15, 2024

How to Iterate Dictionary in Python

In this tutorial we'll see how you can iterate or loop over a dictionary in Python. Some of the options are:

  1. Iterate dictionary directly
  2. Iterate a dictionary using keys method
  3. Iterate a dictionary using values method
  4. Iterate a dictionary using items method

Apart from that we'll also see how to add or remove element from a dictionary while iterating it. See example here.

1. Iterate dictionary directly

If you want to retrieve keys from a dictionary you can use a for loop directly with a dictionary.

def dictIterator(d):
    for k in d:
        print(k)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
#call function
dictIterator(countries)

Output

US
GB
DE
IN

Since you already retrieve keys by this way of iteration, you can also get values by passing keys to dictionary. Here is the changed code

def dictIterator(d):
    for k in d:
        print('key=', k, 'value=', d[k])
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

key= US value= United States
key= GB value= United Kingdom
key= DE value= Germany
key= IN value= India

2. Iterate a dictionary using keys method

Dictionary in Python has a keys() method which returns dictionary's keys as a view object. You can iterate over this view object using for loop.

def dictIterator(d):
    print(type(d.keys()))
    for k in d.keys():
        print('key=', k, 'value=', d[k])
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

<class 'dict_keys'>
key= US value= United States
key= GB value= United Kingdom
key= DE value= Germany
key= IN value= India

As you can see keys() method returns an object of type dict_keys.

3. Iterate a dictionary using values method

Above two ways of iterating a dictionary gives you keys of the dictionary. If you want values then there is also a values() method in dictionary which returns dictionary's values as a view object. You can iterate over this view object using for loop.

def dictIterator(d):
    print(type(d.values()))
    for v in d.values():
        print(v)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

<class 'dict_values'&glt;
United States
United Kingdom
Germany
India

As you can see values() method returns an object of type dict_values.

4. Iterate a dictionary using items method

There is also a items() method in dictionary which returns a view object that contains both key and value.

def dictIterator(d):
    print(type(d.items()))
    for item in d.items():
        print(item)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

<class 'dict_items'>
('US', 'United States')
('GB', 'United Kingdom')
('DE', 'Germany')
('IN', 'India')

As you can see items() method returns an object of type dict_items. Note that each item is of type tuple so you can unpack that tuple to get key and value.

def dictIterator(d):
    for k, v in d.items():
        print('Key =', k, 'Value =', v)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

Key = US Value = United States
Key = GB Value = United Kingdom
Key = DE Value = Germany
Key = IN Value = India

5. Changing dictionary while looping

If you try to make a structural change in a dictionary while iterating it then RuntimeError is raised. Structural change here means adding or deleting items which changes the size of the dictionary while it is iterated. Updating any value doesn't come under structural change.

For example, trying to add new item while iterating.

def dictIterator(d):
    for k in d:
        print(k)
        d['JP'] = 'Japan'
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

RuntimeError: dictionary changed size during iteration

Same way trying to remove an item while iterating the dictionary results in RuntimeError.

def dictIterator(d):
    for k in d:
        print(k)
        if k == 'US':
            del d[k]
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

RuntimeError: dictionary changed size during iteration

In such a scenario where you are going to make a structural change to the dictionary while iterating it, you should make a shallow copy of the dictionary, using copy() method. Then you can iterate over that shallow copy and make changes to the original dictionary.

def dictIterator(d):
    #iterate copy of the dictionary
    for k in d.copy():
        if k == 'US':
            del d[k]
    print(d)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

{'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}

That's all for this topic How to Iterate Dictionary in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. List in Python With Examples
  2. Tuple in Python With Examples
  3. Named Tuple in Python

You may also like-

  1. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  2. Global Keyword in Python With Examples
  3. Bubble Sort Program in Python
  4. String Length in Python - len() Function
  5. Java Stream - Collectors.groupingBy() With Examples
  6. Deque Implementation in Java Using Doubly Linked List
  7. JavaScript let and const With Examples
  8. Spring Integration With Quartz Scheduler

No comments:

Post a Comment