Python индекс элемента словаря

Python индекс элемента словаря

Last updated: Feb 21, 2023
Reading time · 5 min

banner

# Table of Contents

# Get the index of a Key in a Dictionary and access the key

To get the index of a key in a dictionary:

  1. Use the list() class to convert the dictionary to a list of keys.
  2. Use the list.index() method to get the position of the key in the dictionary.
  3. The list.index() method will return the index of the specified key.
Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # 👉️ 1 key = list(my_dict)[1] print(key) # 👉️ name value = list(my_dict.values())[1] print(value) # 👉️ Bobbyhadz

get index of key in dictionary

Once we find the index of the key in a dictionary, we have to convert the dictionary to a list to access it.

We used the list() class to convert the dictionary to a list of keys.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > print(list(my_dict)) # 👉️ ['id', 'name', 'age'] print(list(my_dict.keys())) # 👉️ ['id', 'name', 'age']

We could have also used the dict.keys() method to be more explicit.

The dict.keys method returns a new view of the dictionary’s keys.

The last step is to use the list.index() method to get the position of the key in the dictionary.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # 👉️ 1

The list.index() method returns the index of the first item whose value is equal to the provided argument.

The method raises a ValueError if there is no such item in the list.

We used an if statement to check if the key exists in the dictionary, so the list.index() method will never throw a ValueError .

# Accessing Dictionary keys or values by Index

You can use the index to get the key and value at the specific position.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # 👉️ 1 key = list(my_dict)[index] print(key) # 👉️ name value = list(my_dict.values())[index] print(value) # 👉️ Bobbyhadz

access dictionary keys or values by index

To get the key at the specific position, we just have to convert the dictionary to a list of keys and access the list at the index.

To get the value, we convert the dict.values() view to a list and access it at the index.

The dict.values method returns a new view of the dictionary’s values.

Copied!
my_dict = 'id': 1, 'name': 'bobbyhadz'> print(my_dict.values()) # 👉️ dict_values([1, 'bobbyhadz'])

# Accessing dictionary values by key

Note that unless you have a good reason to access the keys and values in the dictionary using an index, using bracket notation is much more performant.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, 'address': 'country': 'Chile' >, 'tasks': ['dev', 'test'] > print(my_dict['name']) # 👉️ Bobbyhadz print(my_dict['address']) # 👉️ print(my_dict['address']['country']) # 👉️ Chile print(my_dict['tasks'][0]) # 👉️ dev

accessing dictionary values by key

You can specify a key between the square brackets to access the corresponding value.

# Accessing Dictionary Items by Index

You can also use the dict.items() method to get a dictionary key-value pair by index.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > index = 1 key, value = list(my_dict.items())[index] print(key) # 👉️ name print(value) # 👉️ Bobbyhadz

access dictionary items by index

The dict.items method returns a new view of the dictionary’s items ((key, value) pairs).

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > # 👇️ dict_items([('id', 1), ('name', 'Bobbyhadz'), ('age', 30)]) print(my_dict.items())

The dict_items object is not subscriptable (cannot be accessed at an index), so we used the list() class to convert it to a list.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > index = 1 key, value = list(my_dict.items())[index] print(key) # 👉️ name print(value) # 👉️ Bobbyhadz

Python indexes are zero-based, so the first item in a list has an index of 0 , and the last item has an index of -1 or len(a_list) — 1 .

# Getting the index of multiple keys in a dictionary

If you need to get the position of multiple keys in the dictionary, use a for loop.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > keys = ['name', 'age'] for key in keys: if key in my_dict: # name - 1 # age - 2 print(f'key> - list(my_dict).index(key)>')

On each iteration, we check if the key is contained in the dictionary and print the corresponding index.

# Accessing Dictionary keys or values by Index with enumerate()

You can also use the enumerate() function to access dictionary keys or values by index.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > index = 1 key = next( key for idx, key in enumerate(my_dict) if idx == index ) print(key) # 👉️ name # ------------------------------------------------------ value = next( value for idx, value in enumerate(my_dict.values()) if idx == index ) print(value) # 👉️ Bobbyhadz

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, > for index, key in enumerate(my_dict): # 0 id # 1 name # 2 age print(index, key)

On each iteration, we check if the current index is equal to the specified index and return the corresponding key or value.

# Getting all dictionary keys that have a specific value

If you need to get all dictionary keys that have a specific value, use a list comprehension.

Copied!
my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, 'salary': 30, > keys = [key for key, value in my_dict.items() if value == 30] print(keys) # 👉️ ['age', 'salary']

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current value is equal to 30 and return the result.

The keys list only stores the keys of the items that have a value of 30 .

# Using the OrderedDict class instead

As of Python 3.7, the standard dict class is guaranteed to preserve the insertion order of keys.

You can check your version of python by issuing the python —version command.

If you use an older version (than 3.7), use the OrderedDict class instead.

Copied!
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'Bobbyhadz'), ('age', 30)] ) key = list(my_dict)[1] print(key) # 👉️ name value = list(my_dict.values())[1] print(value) # 👉️ Bobbyhadz index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # 👉️ 1

The list() class can also be used to convert the keys of an OrderedDict to a list.

Note that using the OrderedDict class is only necessary if you use a version older than Python 3.7.

Otherwise, use the native dict class as it preserves insertion order.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Python Dictionary Index

Python Dictionary Index

  1. Access the Keys From a Dictionary Using the Index
  2. Access the Values From a Dictionary Using the Index in Python
  3. Access the Key-Value Pairs From a Dictionary Using the Index in Python

Dictionaries are used for storing key-value pairs in Python. In general, we cannot access a dictionary using the index of their elements for other collections like a list or an array.

Before Python 3.7, dictionaries were orderless. Each key-value is given a random order in a dictionary. We can use the OrderedDict() method from the collections module in these cases. It preserves the order in which the key-value pairs are added to the dictionary.

In Python 3.7 and up, the dictionaries were made order-preserving by default.

We can access the keys, values, and key-value pairs using the index in such dictionaries where the order is preserved.

Access the Keys From a Dictionary Using the Index

We will use the keys() method, which returns a collection of the keys. We can use the index to access the required key from this collection after converting it to a list.

Remember to use the list() function with the keys() , values() and items() function. It is because that they do not return traditional lists and do not allow access to elements using the index.

The following demonstrates this.

d = <> d['a'] = 0 d['b'] = 1 d['c'] = 2 keys = list(d.keys()) print(keys[1]) 

When working below Python 3.7, remember to use the OrderedDict() method to create the required dictionary with its order maintained. For example,

from collections import OrderedDict d1 = OrderedDict() d1['a'] = 0 d1['b'] = 1 d1['c'] = 2 keys = list(d1.keys()) print(keys[1]) 

Access the Values From a Dictionary Using the Index in Python

When we want to return a collection of all the values from a dictionary, we use the values() function.

d = <> d['a'] = 0 d['b'] = 1 d['c'] = 2 values = list(d.values()) print(values[1]) 

Access the Key-Value Pairs From a Dictionary Using the Index in Python

The items() function returns a collection of all the dictionary’s key-value pairs, with each element stored as a tuple.

The index can be used to access these pairs from the list.

d = <> d['a'] = 0 d['b'] = 1 d['c'] = 2 values = list(d.items()) print(values[1]) 

Remember to use the OrderedDict() function with all the methods if your version of Python doesn’t preserve the order of the dictionary.

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

Related Article — Python Dictionary

Источник

Читайте также:  Html status code error
Оцените статью