02 CDT - 08 Asccessing Dictionary Elements

Basic Dictionary accessing methods:

  • get(k, [,v]): Fetches the value for key k. If the key is absent, it returns a default value v, or None if no default is provided.
  • keys(): Returns a view of all the keys in the dictionary.
  • values(): Returns a view of all the values in the dictionary.
  • items(): Returns a view of all key-value pairs as tuples.

Getting a value using a key

The get() method is used to retrieve the value associated with a specific key k from the dictionary. If the key k is found, it returns its associated value. However, if the key is not found, it returns a default value v that can be provided. If no default value is provided, the method will return None by default.

Syntax:

dict.get(k, [,v])
  • k: The key whose value you want to retrieve.
  • v: (Optional) A default value to return if the key k is not found.

The get() method is especially useful when you are uncertain whether a key exists in the dictionary, as it avoids raising an error (such as a KeyError) and allows you to specify a default return value.

>>> a = {'colour': 'green', 'points': 5, 'x': 0, 'y': 25}

>>> a.get('points', 'Point not Defined')
5

>>> a.get('axis', 'Axis not Defined')
'Axis not Defined'
  • a.get('points', 'Point not Defined') will return 5 as the value for "points" exists.
  • a.get('axis', 'Axis not Defined') will return 'Axis not Defined' as "axis" is not a key in the dictionary.

In more complex nested dictionaries:

>>> score = {
    'Test1': {'Dhawan': 84, 'Kohli': 200},
    'Test2': {'Dhawan': 50}}

>>> score.get('Test1')
{'Dhawan': 84, 'Kohli': 200}

>>> score.get('Test1["Kohli"]')
>>> # Null

>>> score.get('Test1["Kohli"]', "Player Not Found")
'Player Not Found'
  • score.get('Test1') returns the dictionary associated with "Test1".
  • score.get('Test1["Kohli"]') returns None as the string "Test1['Kohli']" is not a valid key.
  • By passing a second argument "Player Not Found", we get the default message when the key doesn’t exist.

‘dict.keys()’

The keys() method returns a view object that displays a list of all the keys in the dictionary. This view object can be used in loops to iterate over the keys.

You can also directly iterate over the dictionary without calling keys() because by default, when a dictionary is iterated over, it returns the keys.

>>> a = {'colour': 'green', 'points': 5, 'x': 0, 'y': 25}

>>> a.keys()
dict_keys(['colour', 'points', 'x', 'y'])

>>> for key in a.keys():
...     print(key)
colour
points
x
y

‘dict.values()’

The values() method returns a view object that contains all the values stored in the dictionary. It can also be used in loops to iterate over the values.

>>> a = {'colour': 'green', 'points': 5, 'x': 0, 'y': 25}

>>> a.values()
dict_values(['green', 5, 0, 25])

>>> for value in a.values():
...     print(value)
green
5
0
25

‘dict.items()’

The items() method returns a view object that contains a list of key-value pairs in the form of tuples. This is especially useful when you want to iterate over both the keys and their corresponding values.

>>> a = {'colour': 'green', 'points': 5, 'x': 0, 'y': 25}

>>> a.items()
dict_items([('colour', 'green'), ('points', 5), ('x', 0), ('y', 25)])

>>> for key, value in a.items():
...     print(f"Key: {key}, Value: {value}")
Key: colour, Value: green
Key: points, Value: 5
Key: x, Value: 0
Key: y, Value: 25

Looping Through a Dictionary

Looping Through All Key-Value Pairs

To loop through all key-value pairs, we can use the items() method, which allows you to unpack each key-value pair into separate variables.

>>> user_0 = { "username": "efron", "first": "enric", "last": "fermi" }

>>> for key, value in user_0.items():
...     print(f"Key: {key}, Value: {value}")
Key: username, Value: efron
Key: first, Value: enric
Key: last, Value: fermi
>>> fav_lang = { "jen": "Python", "sarah": "C", "edward":"rust", "phil": "python"}

>>> for name, lang in fav_lang.items():
...     print(f"{name}'s favorite language is {lang}.")
... 
jen's favorite language is Python.
sarah's favorite language is C.
edward's favorite language is rust.
phil's favorite language is python.

Looping Through All Keys

We can loop through just the keys in the dictionary by using the keys() method. However, this is optional since iterating over the dictionary directly will by default iterate over the keys.

for name in fav_lang.keys():
Is same as :
for name in fav_lang:

>>> fav_lang = { "jen": "Python", "sarah": "C", "edward":"rust", "phil": "python"}

>>> for name in fav_lang:
...     print(f"{name} took our survey.")
jen took our survey.
sarah took our survey.
edward took our survey.
phil took our survey.

Adding a Condition to check for specific names.

>>> fav_lang = { "jen": "Python", "sarah": "C", "edward":"rust", "phil": "python"}
>>> friends = ["phil", "jen"]
>>> for name in fav_lang:
...     print(f"Hi, {name}")
...     if name in friends:
...             print(f"{name}, I see you love {fav_lang[name]}")
... 
Hi, jen
jen, I see you love Python
Hi, sarah
Hi, edward
Hi, phil
phil, I see you love python

Looping Through Keys in a Particular Order

To iterate through the dictionary keys in a sorted order, you can pass the dictionary keys to the sorted() function.

>>> for name in sorted(fav_lang.keys()):
...     print(f"{name} took our survey.")
edward took our survey.
jen took our survey.
phil took our survey.
sarah took our survey.

Looping Through Values

If you only need the values from the dictionary, you can use the values() method.

>>> fav_lang = { "jen": "python", "sarah": "C", "edward":"rust", "phil": "python"}

>>> for lang in fav_lang.values():
...     print(lang, end = ", ")
python, C, rust, python,

To get only unique values, wrap fav_lang.values() with set() to eliminate duplicates.

>>> for lang in set(fav_lang.values()):
...     print(lang, end = ", ")
rust, python, C,

The set() function ensures that only unique values are iterated, effectively removing any duplicates like "python".