Python iterate over keys

Iterating over dictionary items(), values(), keys() in Python 3

If I understand correctly, in Python 2, iter(d.keys()) was the same as d.iterkeys() . But now, d.keys() is a view, which is in between the list and the iterator. What’s the difference between a view and an iterator? In other words, in Python 3, what’s the difference between

1 Answer 1

I’m not sure if this is quite an answer to your questions but hopefully it explains a bit about the difference between Python 2 and 3 in this regard.

In Python 2, iter(d.keys()) and d.iterkeys() are not quite equivalent, although they will behave the same. In the first, keys() will return a copy of the dictionary’s list of keys and iter will then return an iterator object over this list, with the second a copy of the full list of keys is never built.

The view objects returned by d.keys() in Python 3 are iterable (i.e. an iterator can be made from them) so when you say for k in d.keys() Python will create the iterator for you. Therefore your two examples will behave the same.

The significance in the change of the return type for keys() is that the Python 3 view object is dynamic. i.e. if we say ks = d.keys() and later add to d then ks will reflect this. In Python 2, keys() returns a list of all the keys currently in the dict. Compare:

>>> d = < "first" : 1, "second" : 2 >>>> ks = d.keys() >>> ks dict_keys(['second', 'first']) >>> d["third"] = 3 >>> ks dict_keys(['second', 'third', 'first']) 
>>> d = < "first" : 1, "second" : 2 >>>> ks = d.keys() >>> ks ['second', 'first'] >>> d["third"] = 3 >>> ks ['second', 'first'] 

As Python 3’s keys() returns the dynamic object Python 3 doesn’t have (and has no need for) a separate iterkeys method.

Further clarification

In Python 3, keys() returns a dict_keys object but if we use it in a for loop context for k in d.keys() then an iterator is implicitly created. So the difference between for k in d.keys() and for k in iter(d.keys()) is one of implicit vs. explicit creation of the iterator.

In terms of another difference, whilst they are both dynamic, remember if we create an explicit iterator then it can only be used once whereas the view can be reused as required. e.g.

>>> ks = d.keys() >>> 'first' in ks True >>> 'second' in ks True >>> i = iter(d.keys()) >>> 'first' in i True >>> 'second' in i False # because we've already reached the end of the iterator 

Also, notice that if we create an explicit iterator and then modify the dict then the iterator is invalidated:

>>> i2 = iter(d.keys()) >>> d['fourth'] = 4 >>> for k in i2: print(k) . Traceback (most recent call last): File "", line 1, in RuntimeError: dictionary changed size during iteration 

In Python 2, given the existing behaviour of keys a separate method was needed to provide a way to iterate without copying the list of keys whilst still maintaining backwards compatibility. Hence iterkeys()

Читайте также:  Php date with hours and minutes

Источник

Dictionary Iteration in Python – How to Iterate Over a Dict with a For Loop

Kolade Chris

Kolade Chris

Dictionary Iteration in Python – How to Iterate Over a Dict with a For Loop

In Python, a dictionary is one of the built-in data structures (the others are tuples, lists, and sets). A dictionary is a collection of key:value pairs and you can use them to solve various programming problems.

Dictionaries are very flexible to work with. You can get the keys and values separately, or even together.

This article is about looping over a dictionary with the for loop, but you can also loop through a dictionary with three methods:

  • the key() method: gets you the keys in a dictionary
  • the values() method: gets you the values in a dictionary
  • the items() method: gets you both the keys and values in a dictionary

In the example below, I use those 3 methods to get the keys, values, and items of the dictionary.

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' ># Keys states_keys = states_tz_dict.keys() print(states_keys) # dict_keys(['Florida', 'Hawaii', 'Arizona', 'Colorado', 'Idaho', 'Texas', 'Washington', 'Wisconsin']) # Values tz_values = states_tz_dict.values() print(tz_values) # dict_values(['EST and CST', 'HST', 'DST', 'MST', 'MST and PST', 'CST and MST', 'PST', 'CST']) # Keys and values states_tz_dict_items = states_tz_dict.items() print(states_tz_dict_items) # dict_items([('Florida', 'EST and CST'), ('Hawaii', 'HST'), ('Arizona', 'DST'), ('Colorado', 'MST'), ('Idaho', 'MST and PST'), ('Texas', 'CST and MST'), ('Washington', 'PST'), ('Wisconsin', 'CST')]) 

That’s some iterations we did. But you can also loop through a dictionary with a for loop. That’s what we are going to look at in this tutorial.

What We’ll Cover

How to Iterate through a Dictionary with a for Loop

With the Python for loop, you can loop through dictionary keys, values, or items. You can also loop through the dictionary and put the key:value pair in a list of tuples. We are going to look at them one by one.

Читайте также:  Python and web pages

How to Iterate through Dictionary Keys with a for Loop

Remember how I got the keys of the dictionary with the keys() method in the first part of this article? You can use the same method in a for loop and assign each of the keys to a variable we can call k :

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >for k in states_tz_dict.keys(): print(k) # Result: # Florida # Hawaii # Arizona # Colorado # Idaho # Texas # Washington # Wisconsin 

How to Iterate through Dictionary Values with a for Loop

You can use the values() method in a for loop too, and assign the values to a variable you can call v :

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >for v in states_tz_dict.values(): print(v) # Result: # EST and CST # HST # DST # MST # MST and PST # CST and MST # PST # CST 

How to Iterate through Dictionary Items with a for Loop

The items() method comes in handy in getting the keys and values inside a for loop. This time around, you have to assign two variables instead of one:

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >for k, v in states_tz_dict.items(): print(k,"--->", v) # Result: # Florida ---> EST and CST # Hawaii ---> HST # Arizona ---> DST # Colorado ---> MST # Idaho ---> MST and PST # Texas ---> CST and MST # Washington ---> PST # Wisconsin ---> CST 

Note: You can use any letter for the variable(s) in a for loop. It doesn’t have to be k or v, or k, v.

How to Loop through a Dictionary and Convert it to a List of Tuples

To convert a dictionary to a list of tuples in Python, you still have to use the items() method inside a for loop.

But this time around, you have to surround the loop with square brackets. You also have to assign the loop to a separate variable and wrap the variable for both keys and values in brackets:

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >list_of_tuples = [(k, v) for k, v in states_tz_dict.items()] print(list_of_tuples) # Result: [('Florida', 'EST and CST'), ('Hawaii', 'HST'), ('Arizona', 'DST'), ('Colorado', 'MST'), ('Idaho', 'MST and PST'), ('Texas', 'CST # and MST'), ('Washington', 'PST'), ('Wisconsin', 'CST')] 

Conclusion

In this tutorial, we looked at how to iterate through a dictionary with the for loop.

If you don’t want to use a for loop, you can also use any of the keys() , values() , or items() methods directly like I did in the first part of this article.

Читайте также:  Load stylesheet in html

If you find this article helpful, don’t hesitate to share it on social media.

Kolade Chris

Kolade Chris

Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

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:

for fruit, colour in test: print(f"The fruit is the colour ") 

3 Answers 3

Use items() to get an iterable of (key, value) pairs from test :

for fruit, color in test.items(): # do stuff 

In Python 2, items returns a concrete list of such pairs; you could have used iteritems to get the same lazy iterable instead.

for fruit, color in test.iteritems(): # do stuff 

In Python 3, you will have to change itemiter() to item() for fruit, color in test.items() — since dict.iteritems() was removed and now dict.items() does the same thing

for fruit, colour in test: print "The fruit %s is the colour %s" % (fruit, colour) 
for fruit, colour in test.items(): print "The fruit %s is the colour %s" % (fruit, colour) 
for fruit, colour in test.iteritems(): print "The fruit %s is the colour %s" % (fruit, colour) 

Normally, if you iterate over a dictionary it will only return a key, so that was the reason it error-ed out saying «Too many values to unpack». Instead items or iteritems would return a list of tuples of key value pair or an iterator to iterate over the key and values .

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

for fruit in test: print "The fruit %s is the colour %s" % (fruit, test[fruit]) 

Источник

Оцените статью