PythonDictionaries and sets
dict. items()
Returns a view of (key, value) pairs, the most convenient way to loop over a dictionary.
- Returns
- A
dict_itemsview object with(key, value)tuples. - Changes the original
- No
Example
#Python
modules = {"html": 11, "css": 9, "python": 12}
for course, count in modules.items():
print(f"{course}: {count} modules")
print(list(modules.items())[0])Resultsaved result, you can check it
html: 11 modules
css: 9 modules
python: 12 modules
('html', 11)
Definition and usage
#The items() method returns a view of (key, value) tuples for every entry in the dictionary. In a for loop you can unpack them straight into two variables: for name, score in scores.items().
It's the main tool for processing dictionaries. It combines with dict comprehensions (filtering and transforming entries), with sorted() (sorting by value), and with dict() (building a dictionary from a list of pairs).
Like the other views, items() shows the current state of the dictionary and does not allow changing its size while you loop. Changing the value of an existing key, though, is safe.
Syntax
#Syntax
dict.items()More examples
#Python
scores = {"Jack": 78, "Emma": 92, "Mia": 85}
ranking = sorted(scores.items(), key=lambda pair: pair[1], reverse=True)
print(ranking)
for place, (name, score) in enumerate(ranking, start=1):
print(place, name, score)Resultsaved result, you can check it
[('Emma', 92), ('Mia', 85), ('Jack', 78)]
1 Emma 92
2 Mia 85
3 Jack 78
Python
prices = {"HTML": 49, "Python": 79, "React": 99}
cheap = {name: price for name, price in prices.items() if price < 80}
print(cheap)
for name, price in prices.items():
prices[name] = round(price * 0.9)
print(prices)Resultsaved result, you can check it
{'HTML': 49, 'Python': 79}
{'HTML': 44, 'Python': 71, 'React': 89}
Good practices
#- When sorting by value, pass
key=lambda pair: pair[1]. The result is a list of pairs, which you can turn back into a dictionary withdict(). - While looping over
items()you can change the values of existing keys, but don't add or remove keys.
Related entries
#- dict.keys()Returns a view of the dictionary's keys that always reflects its current contents.
- dict.values()Returns a view of the dictionary values, ready for loops, sums, and lookups.
- Dict comprehensionsA concise way to build a new dictionary by transforming or filtering another collection.
- Unpacking sequencesAssigning the items of a tuple or list to several variables at once.
- sorted()Returns a new, sorted list built from the items of any collection.
Spotted a mistake or missing an example? Write to us.