How to iterate dict python

How to iterate dict python

How to Iterate Through Dictionary in Python? – Definitive Guide

Python dictionary is a data structure that allows you to store values as a key-value pair.

You can iterate through the dictionary in Python using the dict.items() method.

In this tutorial, you’ll learn how to iterate through the dictionary in Python.

If You’re in Hurry…

You can use the below code snippet to iterate over the dictionary items.

You’ll get both the key and value of each item during each iteration.

Snippet

You’ll see all the items in the dictionary are printed as below.

Output

If you’re iterating through the dictionary just to check if a specific key exists in the dictionary, check the guide How to Check If Key Exists in Dictionary.

If You Want to Understand Details, Read on…

In this tutorial, you’ll learn the different methods available to loop through the dictionary keys, values, or the items themselves.

Sample Dictionary

The above dictionary will be used for the demonstration purpose of the complete tutorial. However, tweaks will be made as required to match the demonstration of different use cases.

In most cases, you’ll iterate through the dictionary using for loop and the iterable methods provided by the dictionary to iterate through it.

Table of Contents

Using Keys() Method

You can use the keys() method provided by the dictionary to iterate through the keys of the dictionary.

It returns an iterable of the keys available in the dictionary. Then using for loop, you can iterate through the keys as shown below.

Snippet

Output

Snippet 2

If you want to access the value of the key, then you can use the get() method to get the value of the specific key during each iteration as shown below.

Output

This is how you can iterate through the dictionary keys using for loop and the keys() method provided by the python dictionaries.

Using Values() Method

You can use the values() method provided by the dictionary to iterate through the values of the dictionary items.

It returns an iterable of the values of each item available in the dictionary. Then using for loop, you can iterate through the values as shown below.

Snippet

You’ll see the value of each item in the dictionary printed as below.

Output

Using this method will not give access to the dictionary keys() which is not necessary in most cases. This makes this method the fastest method to iterate through the dictionary.

This is how you can iterate through the dictionary values using for loop and the values() method provided by the python dictionaries.

Using Items() method

You can iterate through the dictionary items using the items() method provided by the python dictionary.

items() method returns a tuple of key-value pair during each iteration.

Then using for loop, you can iterate through the key-value pair and access both the keys and values in the same iteration as shown below.

Snippet

You’ll see the below output. Keys and values will be printed for each iteration and no additional access to the dictionary is necessary to fetch the value of the key.

Output

This is how you can access the items of the dictionary using for loop and the items() method provided by the dictionaries.

Iterating Through Keys Directly Using For Loop

You can access the items in the dictionary using the for loop directly. It iterates through the keys of the dictionary and this is an alternative to using the keys() method.

Snippet

When using the dictionary directly, it returns only the keys during the iteration. You can access the value of each key by using the get() method.

Output

This is how you can loop through a dictionary using the for loop directly without using the methods provided by python dictionaries.

Iterate Over dictionary With Index

You can also iterate through the dictionary using the index of the items.

Snippet

You’ll see all the items printed as shown below.

Output

Iterate Over Dictionary In Alphabetical Order

Dictionaries typically don’t maintain any order. This means the order of the items during the iteration is not guaranteed.

To iterate a dictionary using the specific order, you can use the sorted() function in python.

It’ll sort the object first, then you can use for loop to iterate it.

Sort Using Dictionary Keys

In the below example,

Snippet

You’ll see the below output as the keys will be sorted alphabetically.

Output

Sort Using Dictionary Item Values

To sort the dictionary based on its values, first, you need to create a sorted set of keys.

Then you can iterate the sorted keys set and access the dictionary using the key during each iteration.

In the below example,

Snippet

Output

This is how you can sort dictionaries based on the values.

Iterate Over Dictionary And Update Values

Dictionary is an object which contains a list of values.

Apart from accessing the items in the dictionary, you may also need to update the values of the item in the dictionary.

In this section, you’ll learn how to iterate over dictionary and update values based on some condition.

Snippet

Once the script is executed, you’ll see the value » value updated for the key five as shown below.

Output

This is how you can loop through the dictionary and update values.

Conclusion

To summarize, you’ve learned the different methods to loop through the dictionary in python and you’ve also learned how to apply this method in different use-cases.

How to iterate over a dictionary

What I want is to iterate over test and get the key and value together. If I just do a for item in test: I get the key only.

An example of the end goal would be:

How to iterate dict python. Смотреть фото How to iterate dict python. Смотреть картинку How to iterate dict python. Картинка про How to iterate dict python. Фото How to iterate dict python

How to iterate dict python. Смотреть фото How to iterate dict python. Смотреть картинку How to iterate dict python. Картинка про How to iterate dict python. Фото How to iterate dict python

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

In Python 2 you’d do:

In Python 3, use items() instead ( iteritems() has been removed):

This is covered in the tutorial.

Alternatively you can always access the value via key as in the following example

The normal for key in mydict iterates over keys. You want to iterate items:

Not the answer you’re looking for? Browse other questions tagged python or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

How to iterate through a python dictionary

A python Dictionary is one of the important data structure which is extensively used in data science and elsewhere when you want to store the data as a key-value pair. In this post we will take a deep dive into dictionaries and ways to iterate over dictionary and find out how to sort a dictionary values and other operations using dictionary data structure

Basically a dictionary in python is a mapping object where it maps a key to a value. The keys are hashable values which are mapped to values. The keys are arbitrary values and any values that are not hashable that is values containing list or other mutable types may not be used as Keys. Even it is not a good practice to use numeric values as keys also.

How to create a Dictionary?

We can create a Dictionary using key:value pairs separated by commas or using the dict constructor

Using comma separated key value pair

Using dict constructor

Convert two list into a dictionary

Convert list of tuples(Key,Value) into a dictionary

What’s Changed for Dictionary in Python 3.6

Dictionaries got ordered in Python 3.6 that means it remembers the order of insertion of key and value pairs. It means that keyword arguments can now be iterated by their creation order, which is basically the cpython implementation of python

The memory usage of this new dictionary implementation will also reduce the memory usage by 20-25%

Here is an example from the python dev mailing list for the implementation of new dict in python 3.6

Create a function to get the dictionary keys

Calling the above function in Python 3.5 and before returns an un-ordered dict_keys. Check the output the keys are randomly ordered

Output in Python 3.5 and before:

Calling the same function in python3.6 and above returns a dict_keys in the same order as it has been passed in the function

Output in Python 3.6 and above:

Iterating thru a dictionary

As a python developer or data scientists you will be working on dictionaries a lot and there are calculations or actions that needs to be performed while working through the dictionary keys and values

In this section we will see what are the ways you can retrieve the data from the dictionary

Python supports a concept of iteration over containers and An iterator needs to define two methods: iter() and next(). Usually, the object itself defines the next() method, so it just returns itself as the iterator.

the iter defines the next method which will be called by statements like for and in to yield the next item, and next() should raise the StopIteration exception when there are no more items

Hope this clears how the iterator works on the dictionary

These methods are used by for and in statements, so what it means is if you put a dictionary under a for loop then it will automatically call the iter() method and iterate over the dictionaries keys

Iterate dictionary using keys

Output:

Dictionary view objects

This provide a window of the dictionary entries and when any of the item changes in the dict then it will reflect those changes in the views

As per the python official documentation:

The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes

Length of Dictionary

This returns number of key,value pairs in the dictionary

list of dictionary keys

the keys() function returns dict_keys() which is wrapped with the list to get a list object.

Output:

list of dictionary values

the values() function returns dict_values() which is wrapped with the list to get a list object

Output:

Iterate thru dict values

The dict_values is an iterable so you can directly iterate through the values of dictionaries using for loop

Output:

Iterate thru dict keys

The dict_keys is an iterable so you can directly iterate through the keys of dictionaries using for loop

Output:

Iterate key, value pair using dict.items

This returns a (key,value) pair which is a tuple object.

Output:

Dictionary Comprehension

It is a syntactical extension to list comprehension. It produce a dictionary object and you can’t add keys to an existing dictionary using this

You group the expression using curly braces and the left part before the for keyword expresses both a key and a value, separated by a colon

Output:

Dictionary Get Key

Let’s understand this with a small example

Here is a dictionary of city and respective states:

We have to output the state name when user enters a city

When city is in Dictionary Key:

Output:

You live in state of North Carolina

When city is not in Dictionary Key:

Output:

You live in state of None

Unpack a Dictionary using itemgetter

You can unpack a dictionary using operator.itemgetter() function which is helpful if you want to get the values from the dictionary given a series of keys

Look at this example below we are extracting the values of keys a, b and c using itemgetter

Sorting

There are certain situations where you need to sort the dictionary either by key or values. You can achieve this using sorted() function. In the below section we will see how to sort the dictionary by keys and values

if you are using python 3.6 and above then do not worry the dictionary are ordered data structured and can be easily sorted using sorted() function inside a dictionary comprehension

Sorting Dictionary by Keys

You can pass the entire dictionary dict_items as an argument to sorted function and it will return a list of tuples after sorting which can be converted back to dictionary using the dict constructor

Output:

You can see the output the dictionary keys are sorted alphabetically

Sorting Dictionary by Values

You can also sort the dictionary with their values using the sorted() function and another argument key and value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes

By default it gives the result in ascending order. You can see the list of keys that is returned here based on the values of each of the corresponding keys arranged in ascending order

Ascending Order

Output:

if you want the list of keys to be in descending order above then add another argument called reverse as True and this will give the keys based on their values arranged in descending order

Descending order

Output:

Enumerate Dictionary

You can also enumerate through the dictionary and can get the index of each of the key

Just remember d.keys(), d.values() returns a dict_keys object which behaves a lot more like a set than a list

Therefore, dict.values() needs to be wrapped in a list. You can see in the below code we have used list(d.values())[index]

Output:

Filter Dictionary

You can filter a dictionary using the dictionary comprehension which will create a new dictionary based on the filter criteria.

Output:

dict.pop()

If you aren’t sure about the key exists in dictionary then use dict.pop().

This will return d[‘f’] if key exists in the dictionary, and None otherwise.

If the second parameter is not specified (i.e. d.pop(‘f’)) and key does not exist, a KeyError is raised.

Merge two or more Dictionaries

You can use the dictionary unpacking operator ** to merge two or more dictionary into one single dictionary and then you can iterate this new merged dictionary

Here is an example:

Output:

Conclusion:

We have reached to the end of this comprehensive and detailed post on iterating through dictionaries. So here is what we have learned so far through our journey thru this blog

I have tried to cover all the possible ways to iterate through a dictionary and explain different ways to work with dictionary efficiently.

Still if there are anything you feel should be included in this post or can be done in more optimized way then please leave a comment below.

Updated: December 4, 2019

Share on

You may also enjoy

Tensorflow available GPU and it’s details

In this post we will see how to find all the available CPU and GPU devices on the host machine and get the device details and other info like it’s Memory usa.

Pandas compare columns in two data frames

Pandas select rows and columns in MultiIndex dataframe

Pandas filter dates by month, hour, day and last N days & weeks

We have dataframe with dates or timestamps columns and we would like to filter the rows by Month, Hour, day or by last n days from today’s date.

3 Ways To Iterate Over Python Dictionaries Using For Loops

…and other answers to the most popular Stack Overflow questions on Python dictionaries.

How to iterate dict python. Смотреть фото How to iterate dict python. Смотреть картинку How to iterate dict python. Картинка про How to iterate dict python. Фото How to iterate dict python

Hope you’ll find them useful too! Now enjoy the article 😀

Introduction

A Python dictionary is defined as a collection of data values, in which items are held as key-value pairs. For this reason, dictionaries are also known as associative arrays.

If you are relatively new to Python, or you are preparing for your next coding round, you might have stumbled upon a number of algorithms that require to interact with dictionaries.

However, it seems that dictionaries keep generating interest not only among newbies, but also among more experienced developers. In effect, looking at the top Stack Overflow Python questions of all times, it seems that three of the most voted topics are:

In this article, I will attempt to provide you with a succinct and clear answer to each one of this questions. This will spare you from going through dozens of comments on the web.

Let’s start from the top! 👆👆🏽👆🏻

How to iterate over dictionaries using a ‘for’ loop?

To answer this question, I have created a dictionary including data of a mock online banking transaction:

Method 1: Iteration Using For Loop + Indexing

The easiest way to iterate through a dictionary in Python, is to put it directly in a for loop. Python will automatically treat transaction_data as a dictionary and allow you to iterate over its keys.

Then, to also get access to the values, you can pass each key to the dictionary using the indexing operator [] :

As you can see, the keys are not ordered alphabetically. To achieve that, you should simply pass transaction_data to the sorted() method:

This is particularly handy when you just need to iterate over the keys of a dictionary, but it can also be used in combination with the indexing operator to retrieve values:

In order to iterate over the keys and the values of the transaction_data dictionary, you just need to ‘unpack’ the two items embedded in the tuple as shown below:

Note that k and v are just standard aliases for ‘key’ and ‘value’, but you can opt for an alternative naming convention too. For example using a and b leads to the same output:

In order to unpack the key-value pairs belonging to each nested dictionary, you can use the following loop:

How to check if a given key already exists in a dictionary?

You can check membership in Python dictionaries using the in operator.

Likewise, to check if the value GBP was already assigned to a key in the dictionary, you could run:

However, the check above won’t immediately tell you if GBP is the value assigned to the send_currency key or the target_currency key. In order to confirm that, you can pass a tuple to the values() method:

If the transaction_data dictionary included hundreds of values, this would be the perfect way to check that GBP is indeed the send_currency for that specific transaction.

How to add a new keys to a dictionary?

Lastly, let’s pretend that, at some point, the Analytics Team asked you to add both the user_address and the user_email fields to the the data available in the dictionary. How would you achieve that?

There are two main method:

Conclusion

In this article, I shared 3 methods to iterate through Python dictionaries with ‘for’ loops and extract key-value pairs efficiently. However, be aware that even more ‘pythonic’ solutions exist ( i.e. dictionary comprehensions).

Despite being a relatively basic topic, “ how to iterate over Python dictionaries?”, is one of the most voted questions ever asked on Stack Overflow.

For this reason, I also answered to other two extremely popular Stack Overflow questions about checking membership and adding new key-value pairs to Python dictionaries.

My hope is that you will use this article to clarify all your doubts about dictionaries in the same place. Learning code is fun and will change your life for good, so keep learning!

A Note For My Readers

This post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase.

Python: Iterate / Loop over Dictionary (All key-value pairs)

In this article we will discuss different ways to iterate over all key-value pairs of a dictionary.

Table of Contents:

Suppose we have a dictionary with string as key and integers as value i.e.

Now let’s see how to iterate over this dictionary using 4 different techniques i.e.

Iterate over a dictionary using for loop over keys

A dictionary object can also be used as an iterable obejct, to iterate over all keys of dictionary. So, we can easily apply for loop on a dictionary. By using for in dictionary, it loops through all the keys in dictionary. For each key we will select the value associated with it and print them.

Output:

Its not an efficient solution because we are iterating over all the keys in dictionary and for each key we are again searching for its associated value.

Let’s see an efficient method i.e.

Iterate over key-value pairs of dictionary using dict.items()

In Python, dictionary class provides a function items(), which returns an sequence of all key-value pairs of dictionary. This sequence is an iterable View object of all key,value elements in the dictionary. Its backed by original dictionary. Let’s use this to iterate over all key-value pairs of dictionary,

Output:

As, view object is backed by original dictionary, therefore any changes made in dictionary will be reflected in it.
For example,

Take a view object of dictionary i.e.

Output

Now modify the dictionary

Now same view object will also be modified because its backed by original dictionary

Read More,

Iterate over a dictionary using list comprehension

As dictionary’s items() function returns an iterable sequence of key-value pairs, so we can also use this list comprehension to iterate over all pairs of diction. For example,

Output:

Iterate over specific key-value pairs of dictionary

We can also iterate over specific key-value pairs of dictionary, it means the pairs which satisfy a certain condition. For example, loop our pairs of dictionary, where value is greater than 20,

Output:

Summary:

We learned about four different ways to iterate over all key-value pairs of dictionary.

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Related Posts

Convert a List to a String in Python

Convert a List of Characters into a String in Python

Convert a JSON String to a Dictionary in Python

How to Concatenate String and Integer in Python?

Check if a String is Empty in Python

How to Fill out a String with spaces in Python?

Split Multi-Line String into multiple Lines in Python

Split string at every Nth character in Python

Check if a character in a string is a letter in Python

Check if multiple strings exist in a string in Python

Convert String representation of List to a List in Python

Get unique values from a List in Python

Find the index of an item in List in Python

Get number of elements in a list in Python

Count occurrences of an item in List in Python

How to concatenate two lists in Python?

How to Write a String to a Text File in Python?

Python – Remove Punctuations from a String

Remove specific characters from a string in Python

Print a variable & string on the same line in Python

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Advertisements

Advertisements

Recent Posts

Python Tutorials

Looking for Something

C++ / C++11 Tutorials

Terms of Use

Terms and Policies

Python Tutorials

Favorite Sites

Disclaimer

Terms & Policy

Copyright © 2022 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *