Ways to Access Dictionary items


Access Dictionary items

As the dictionary stores data in the key-value pair, to access dictionary items indexes cannot be used. The key has to be used to access the values. Let us explore various ways to access the dictionary items.

Ways to Access Dictionary items

Using keys

To access dictionary items, we use the key inside the square brackets. In this approach, Python returns the Key Error in case the item does not exist in the dictionary.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
emp_details['emp_id']
Out[1]:
200

We get KeyError, if key does not exists.

In [2]:
emp_details['salary']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-bd2b8840060b> in <module>
----> 1 emp_details['salary']

KeyError: 'salary'

Using the get() method

While using the key to access the dictionary items, if the key does not exist, we get the KeyError. The get() method can also be used to access the elements of the dictionary. Using the get() method, we do not get any key error if the key does not exist.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
emp_details.get('emp_id')
Out[1]:
200

No KeyError, if key does not exists.

In [2]:
emp_details.get('salary')

The items() method

The items() method returns the view of tuples, and each tuple contains the key and its value. This method can be used with the for loop to traverse over the key and the corresponding values.

As it is a view of the dictionary items, so in case we add a new item to the dictionary, then the items variable gets updated automatically. We need not initiate the variable again.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
items = emp_details.items()
print(items)
dict_items([('first_name', 'Tim'), ('last_name', 'Cook'), ('emp_id', 200), ('bill', 200.2)])

Salary is added after the initialization of the items variables and items variable gets updated automatically.

In [2]:
emp_details["salary"] = 35000
print(items)
dict_items([('first_name', 'Tim'), ('last_name', 'Cook'), ('emp_id', 200), ('bill', 200.2), ('salary', 35000)])

Using for loop.

In [3]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}

for key, value in emp_details.items():
    print(key, "-", value)
first_name - Tim
last_name - Cook
emp_id - 200
bill - 200.2

The keys() method

The keys() method returns the view of keys. A loop can be used to traverse the list.

Please note, it is view of all keys in the dictionary. In case we add a new item to the dictionary, then the emp_keys variable gets updated automatically, we need not initiate it again.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
emp_keys = emp_details.keys()
print(emp_keys)
dict_keys(['first_name', 'last_name', 'emp_id', 'bill'])

Salary is added after the initialization of the emp_keys variables and emp_keys variable gets updated automatically.

In [2]:
emp_details["salary"] = 35000
print(emp_keys)
dict_keys(['first_name', 'last_name', 'emp_id', 'bill', 'salary'])

Using for loop.

In [3]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}

for key in emp_details.keys():
    print(key)
first_name
last_name
emp_id
bill

The values() method

The values() method returns the view of values in the dictionary which can be traversed using the for loop.

Again, the values() method actually returns the view of all values in the dictionary. In case we add a new item to the dictionary, the emp_values variable gets updated automatically.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
emp_values = emp_details.values()
print(emp_values)
dict_values(['Tim', 'Cook', 200, 200.2])

Salary is added after the initialization of the emp_values variables and emp_values variable gets updated automatically.

In [2]:
emp_details["salary"] = 35000
print(emp_values)
dict_values(['Tim', 'Cook', 200, 200.2, 35000])

Using for loop.

In [3]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}

for item in emp_details.items():
    print(item)
('first_name', 'Tim')
('last_name', 'Cook')
('emp_id', 200)
('bill', 200.2)

Using List Comprehension

Using comprehension is also one of the approaches to access dictionary items. With comprehension, we can manually create the list of tuples with keys and values. A list containing each key-value pair as the list can also be created, as shown in the example.

Example of Tuple inside List.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
employee_list = [(key, emp_details[key]) for key in emp_details]

print(employee_list)
[('first_name', 'Tim'), ('last_name', 'Cook'), ('emp_id', 200), ('bill', 200.2)]

Example of List inside List.

In [2]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
employee_list = [[key, emp_details[key]] for key in emp_details]

print(employee_list)
[['first_name', 'Tim'], ['last_name', 'Cook'], ['emp_id', 200], ['bill', 200.2]]

Using enumerate() function

Python has a built-in function enumerate() to iterate over all the container data types like, list, tuple, dictionary, etc. The enumerate() function will return the index position of the item along with the item. These index positions start from 0.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i, employee in enumerate(emp_details.items()):
    print(i, "-", employee)
0 - ('first_name', 'Tim')
1 - ('last_name', 'Cook')
2 - ('emp_id', 200)
3 - ('bill', 200.2)

Check Exits

We use the in keyword to check if the key exists in the dictionary.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
if 'last_name' in emp_details:
    print("Last Name =", emp_details['last_name'])
Last Name = Cook

References

  1. Python – Access Dictionary Items
  2. Getting Values from a Dictionary in Python