Get key and value in dict python

This article describes how to get the value from a dictionary (dict type object) by the key in Python.

  • Get value from dictionary with dict[key] (KeyError for non-existent keys)
  • Use dict.get() to get the default value for non-existent keys

If you want to extract keys by the value, see the following article.

  • Get key from value in dictionary in Python

Get value from dictionary with dict[key] (KeyError for non-existent keys)

In Python, you can get the value from a dictionary by specifying the key like dict[key].

d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}

print(d['key1'])
# val1

In this case, KeyError is raised if the key does not exist.

# print(d['key4'])
# KeyError: 'key4'

Note that it is no problem to specify a non-existent key if you want to add a new element.

d['key4'] = 'val4'
print(d)
# {'key1': 'val1', 'key2': 'val2', 'key3': 'val3', 'key4': 'val4'}

For more information about adding items to the dictionary, see the following article.

  • Merge multiple dictionaries and add items to a dictionary in Python

Use in to check if the key exists in the dictionary.

  • Check if key/value exists in dictionary in Python

Use dict.get() to get the default value for non-existent keys

You can use the get() method of the dictionary (dict) to get any default value without an error if the key does not exist.

  • Built-in Types - dict.get() — Python 3.9.1 documentation

Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

print(d.get('key1'))
# val1

print(d.get('key5'))
# None

You can specify the default value to be returned when the key does not exist in the second argument.

print(d.get('key5', 'NO KEY'))
# NO KEY

print(d.get('key5', 100))
# 100

The original dictionary itself does not change.

print(d)
# {'key1': 'val1', 'key2': 'val2', 'key3': 'val3', 'key4': 'val4'}

Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value, so that they can be retrieved efficiently.

Let’s discuss various ways of accessing all the keys along with their values in Python Dictionary.

Method #1 : Using in operator

Most used method that can possibly get all the keys along with its value, in operator is widely used for this very purpose and highly recommended as offers a concise method to achieve this task.

test_dict = {"Geeks" : 1, "for" : 2, "geeks" : 3}

print ("Original dictionary is : " + str(test_dict))

print ("Dict key-value are : ")

for i in test_dict :

    print(i, test_dict[i])

Output:

Original dictionary is : {'geeks': 3, 'for': 2, 'Geeks': 1}
Dict key-value are : 
geeks 3
for 2
Geeks 1

Method #2 : Using list comprehension

This method also uses the method similar to above method, just binds the logic into one list and returns the key value pairs of dictionary as tuples of key and value in the list.

test_dict = {"Geeks" : 1, "for" : 2, "geeks" : 3}

print ("Original dictionary is : " + str(test_dict))

print ("Dict key-value are : ")

print([(k, test_dict[k]) for k in test_dict])

Output:

Original dictionary is : {'Geeks': 1, 'for': 2, 'geeks': 3}
Dict key-value are : 
[('Geeks', 1), ('for', 2), ('geeks', 3)]

Method #3 : Using dict.items()

items(), in dictionary iterates over all the keys and helps us to access the key-value pair one after the another in the loop and is also a good method to access dictionary keys with value.

test_dict = {"Geeks" : 1, "for" : 2, "geeks" : 3}

print ("Original dictionary is : " + str(test_dict))

print ("Dict key-value are : ")

for key, value in test_dict.items():

    print (key, value)

Output:

Original dictionary is : {'geeks': 3, 'for': 2, 'Geeks': 1}
Dict key-value are : 
geeks 3
for 2
Geeks 1

 
Method #4 : Using enumerate()

Python also offers enumerate() with helps to iterate over all kinds of containers, be it dictionary or a list. The power of this function can also be utilized to perform this task. It also additionally helps to access the named index of position of the pair in dictionary.

test_dict = {"Geeks" : 1, "for" : 2, "geeks" : 3}

print ("Original dictionary is : " + str(test_dict))

print ("Dict key-value are : ")

for i in enumerate(test_dict.items()):

    print (i)

Output:

Original dictionary is : {'geeks': 3, 'Geeks': 1, 'for': 2}
Dict key-value are : 
(0, ('geeks', 3))
(1, ('Geeks', 1))
(2, ('for', 2))


How do you iterate keys and values in Python?

There are multiple ways to iterate over a dictionary in Python..
Access key using the build .keys().
Access key without using a key().
Iterate through all values using .values().
Iterate through all key, and value pairs using items().
Access both key and value without using items().
Print items in Key-Value in pair..

How do you get a specific value from a dictionary in Python?

In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.

How do you find the values of a key in a list of dictionaries in Python?

Use a list comprehension to find the values of a key in a list of dictionaries. Use the list comprehension syntax [dict[key] for dict in list_of_dicts] to get a list containing the corresponding value for each occurrence of key in the list of dictionaries list_of_dicts .

Does dict values () return a list?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly.