Как обратиться к ключу словаря python
Перейти к содержимому

Как обратиться к ключу словаря python

  • автор:

Get key by value in dictionary

I made a function which will look up ages in a Dictionary and show the matching name:

I know how to compare and find the age I just don’t know how to show the name of the person. Additionally, I am getting a KeyError because of line 5. I know it’s not correct but I can’t figure out how to make it search backwards.

Neuron's user avatar

43 Answers 43

Or in Python 3.x:

Basically, it separates the dictionary’s values in a list, finds the position of the value you have, and gets the key at that position.

More about keys() and .values() in Python 3: How can I get list of values from dict?

There is none. dict is not intended to be used this way.

If you want both the name and the age, you should be using .items() which gives you key (key, value) tuples:

You can unpack the tuple into two separate variables right in the for loop, then match the age.

You should also consider reversing the dictionary if you’re generally going to be looking up by age, and no two people have the same age:

so you can look up the name for an age by just doing

I’ve been calling it mydict instead of list because list is the name of a built-in type, and you shouldn’t use that name for anything else.

You can even get a list of all people with a given age in one line:

or if there is only one person with each age:

which will just give you None if there isn’t anyone with that age.

Finally, if the dict is long and you’re on Python 2, you should consider using .iteritems() instead of .items() as Cat Plus Plus did in his answer, since it doesn’t need to make a copy of the list.

I thought it would be interesting to point out which methods are the quickest, and in what scenario:

Here’s some tests I ran (on a 2012 MacBook Pro)

Results from profile.run() on each method 100,000 times:

So this shows that for a small dict, method 1 is the quickest. This is most likely because it returns the first match, as opposed to all of the matches like method 2 (see note below).

Interestingly, performing the same tests on a dict I have with 2700 entries, I get quite different results (this time run 10,000 times):

So here, method 3 is much faster. Just goes to show the size of your dict will affect which method you choose.

  • Method 2 returns a list of all names, whereas methods 1 and 3 return only the first match.
  • I have not considered memory usage. I’m not sure if method 3 creates 2 extra lists ( keys() and values() ) and stores them in memory.

one line version: (i is an old dictionary, p is a reversed dictionary)

explanation : i.keys() and i.values() returns two lists with keys and values of the dictionary respectively. The zip function has the ability to tie together lists to produce a dictionary.

Warning : This will work only if the values are hashable and unique.

pfabri's user avatar

I found this answer very effective but not very easy to read for me.

To make it more clear you can invert the key and the value of a dictionary. This is make the keys values and the values keys, as seen here.

or for Python 3, (thanks @kkgarg)

which is essentially the same that this other answer.

Rafael Valero's user avatar

Try this one-liner to reverse a dictionary:

If you want to find the key by the value, you can use a dictionary comprehension to create a lookup dictionary and then use that to find the key from the value.

we can get the Key of dict by :

Jean-François Fabre's user avatar

Sakhri Houssem's user avatar

You can get key by using dict.keys() , dict.values() and list.index() methods, see code samples below:

Andriy Ivaneyko's user avatar

Here is my take on this problem. 🙂 I have just started learning Python, so I call this:

«The Understandable for beginners» solution.

Consider using Pandas. As stated in William McKinney’s «Python for Data Analysis’

Another way to think about a Series is as a fixed-length, ordered dict, as it is a mapping of index values to data values. It can be used in many contexts where you might use a dict.

To query your series do the following:

If you need to do anything else with the output transforming the answer into a list might be useful:

The output is as follows:

Here, recover_key takes dictionary and value to find in dictionary. We then loop over the keys in dictionary and make a comparison with that of value and return that particular key.

One line solution using list comprehension, which returns multiple keys if the value is possibly present multiple times.

tbjorch's user avatar

Jean-François Fabre's user avatar

get multiple data

Carson's user avatar

I glimpsed all answers and none mentioned simply using list comprehension?

This Pythonic one-line solution can return all keys for any number of given values (tested in Python 3.9.1):

Frank Wang's user avatar

it’s answered, but it could be done with a fancy ‘map/reduce’ use, e.g.:

I tried to read as many solutions as I can to prevent giving duplicate answer. However, if you are working on a dictionary which values are contained in lists and if you want to get keys that have a particular element you could do this:

Now lets find names that have 24 in their values.

This would work with multiple values as well.

Ozkan Serttas's user avatar

Just my answer in lambda and filter .

Bishwas Mishra's user avatar

already been answered, but since several people mentioned reversing the dictionary, here’s how you do it in one line (assuming 1:1 mapping) and some various perf data:

if you think it’s not 1:1, you can still create a reasonable reverse mapping with a couple lines:

how slow is this: slower than a simple search, but not nearly as slow as you’d think — on a ‘straight’ 100000 entry dictionary, a ‘fast’ search (i.e. looking for a value that should be early in the keys) was about 10x faster than reversing the entire dictionary, and a ‘slow’ search (towards the end) about 4-5x faster. So after at most about 10 lookups, it’s paid for itself.

the second version (with lists per item) takes about 2.5x as long as the simple version.

Also had some interesting results with ifilter. Theoretically, ifilter should be faster, in that we can use itervalues() and possibly not have to create/go through the entire values list. In practice, the results were. odd.

So, for small offsets, it was dramatically faster than any previous version (2.36 *u*S vs. a minimum of 1.48 *m*S for previous cases). However, for large offsets near the end of the list, it was dramatically slower (15.1ms vs. the same 1.48mS). The small savings at the low end is not worth the cost at the high end, imho.

Как обратиться к ключу словаря python

Словарь (dictionary) в языке Python хранит коллекцию элементов, где каждый элемент имеет уникальный ключ и ассоциированое с ним некоторое значение.

Определение словаря имеет следующий синтаксис:

В фигурных скобках через запятую определяется последовательность элементов, где для каждого элемента сначала указывается ключ и через двоеточие его значение.

В словаре users в качестве ключей используются числа, а в качестве значений — строки. То есть элемент с ключом 1 имеет значение «Tom», элемент с ключом 2 — значение «Bob» и т.д.

В словаре emails в качестве ключей используются строки — электронные адреса пользователей и в качестве значений тоже строки — имена пользователей.

Но необязательно ключи и строки должны быть однотипными. Они могу представлять разные типы:

Мы можем также вообще определить пустой словарь без элементов:

Преобразование списков и кортежей в словарь

Несмотря на то, что словарь и список — непохожие по структуре типы, но тем не менее существует возможности для отдельных видов списков преобразования их в словарь с помощью встроенной функции dict() . Для этого список должен хранить набор вложенных списков. Каждый вложенный список должен состоять из двух элементов — при конвертации в словарь первый элемент станет ключом, а второй — значением:

Подобным образом можно преобразовать в словарь двухмерные кортежи, которые в свою очередь содержать кортежи из двух элементов:

Получение и изменение элементов

Для обращения к элементам словаря после его названия в квадратных скобках указывается ключ элемента:

Например, получим и изменим элементы в словаре:

Если при установки значения элемента с таким ключом в словаре не окажется, то произойдет его добавление:

Но если мы попробуем получить значение с ключом, которого нет в словаре, то Python сгенерирует ошибку KeyError:

И чтобы предупредить эту ситуацию перед обращением к элементу мы можем проверять наличие ключа в словаре с помощью выражения ключ in словарь . Если ключ имеется в словаре, то данное выражение возвращает True:

Также для получения элементов можно использовать метод get , который имеет две формы:

get(key) : возвращает из словаря элемент с ключом key. Если элемента с таким ключом нет, то возвращает значение None

get(key, default) : возвращает из словаря элемент с ключом key. Если элемента с таким ключом нет, то возвращает значение по умолчанию default

Удаление

Для удаления элемента по ключу применяется оператор del :

Но стоит учитывать, что если подобного ключа не окажется в словаре, то будет выброшено исключение KeyError. Поэтому опять же перед удалением желательно проверять наличие элемента с данным ключом.

Другой способ удаления представляет метод pop() . Он имеет две формы:

pop(key) : удаляет элемент по ключу key и возвращает удаленный элемент. Если элемент с данным ключом отсутствует, то генерируется исключение KeyError

pop(key, default) : удаляет элемент по ключу key и возвращает удаленный элемент. Если элемент с данным ключом отсутствует, то возвращается значение default

Если необходимо удалить все элементы, то в этом случае можно воспользоваться методом clear() :

Копирование и объединение словарей

Метод copy() копирует содержимое словаря, возвращая новый словарь:

Метод update() объединяет два словаря:

При этом словарь users2 остается без изменений. Изменяется только словарь users, в который добавляются элементы другого словаря. Но если необходимо, чтобы оба исходных словаря были без изменений, а результатом объединения был какой-то третий словарь, то можно предварительно скопировать один словарь в другой:

Перебор словаря

Для перебора словаря можно воспользоваться циклом for:

При переборе элементов мы получаем ключ текущего элемента и по нему можем получить сам элемент.

Другой способ перебора элементов представляет использование метода items() :

Метод items() возвращает набор кортежей. Каждый кортеж содержит ключ и значение элемента, которые при переборе мы тут же можем получить в переменные key и value.

Также существуют отдельно возможности перебора ключей и перебора значений. Для перебора ключей мы можем вызвать у словаря метод keys() :

Правда, этот способ перебора не имеет смысла, так как и без вызова метода keys() мы можем перебрать ключи, как было показано выше.

Для перебора только значений мы можем вызвать у словаря метод values() :

Комплексные словари

Кроме простейших объектов типа чисел и строк словари также могут хранить и более сложные объекты — те же списки, кортежи или другие словари:

В данном случае значение каждого элемента словаря в свою очередь представляет отдельный словарь.

Для обращения к элементам вложенного словаря соответственно необходимо использовать два ключа:

Но если мы попробуем получить значение по ключу, который отсутствует в словаре, Python сгенерирует исключение KeyError:

Чтобы избежать ошибки, можно проверять наличие ключа в словаре:

Во всем остальном работа с комплексными и вложенными словарями аналогична работе с обычными словарями.

Словари в Python 3

Словари – это изменяемый неупорядоченный тип данных, состоящий из коллекций произвольных объектов в формате «ключ: значение». Также словари называются хэш-таблицами или ассоциативными массивами.

Обычно словари используются для хранения связанных между собой данных; например, пара может состоять из имени пользователя и его ID. Элементы словарей берутся в фигурные скобки < >.

Словарь выглядит так:

Чтобы отделить ключ от значения, в словарях используются символы двоеточия. Пары «ключ: значение» отделяются друг от друга запятыми.

Ключи всегда находятся слева от двоеточия. Ключ может быть представлен любым неизменяемым типом данных. В приведённом выше примере содержатся такие ключи:

  • ‘username’
  • ‘online’
  • ‘followers’

В данном случае ключи выражены строками.

Слева от двоеточия находятся значения. Значение может выражаться любым типом данных. В словаре выше мы видим такие значения:

  • ‘8host-blog’
  • True
  • 987

Первый ключ представлен строкой, второй – логическим значением, а третий – целым числом.

Читайте также:

Попробуйте отобразить словарь 8host:

Обратите внимание: порядок пар «ключ: значение» изменился. Это произошло потому, что словари являются неупорядоченным типом данных. В отличие от списков и кортежей, словари не сохраняют порядок своих элементов и, соответственно, не индексируются.

Читайте также:

В словарях пары всегда расположены в случайном порядке. Однако сами пары «ключ: значение» всегда остаются неизменными, благодаря чему и осуществляется доступ к данным.

Доступ к элементам словаря

Поскольку элементы словаря не упорядочены, к ним невозможно получить доступ по индексу. Чтобы получить доступ к значению, нужно вызвать соответствующий ключ.

Доступ к данным по ключу

Словари могут стать важной частью разработанной в Python программы.

К примеру, чтобы вывести только имя пользователя в приведённом выше словаре, нужно ввести:

Словари ведут себя как базы данных, потому что для доступа к значению используется ключ, а не индекс.

Таким же образом можно вызвать и остальные значения этого словаря:

print(8host[‘followers’])
987
print(8host[‘online’])
True

Доступ к данным с помощью функций

Доступ к значениям можно получить не только с помощью ключей, но и при помощи функций.

  • dict.keys() – выводит ключи словаря.
  • dict.values() – выводит значения словаря.
  • dict.items() – выводит пары в виде кортежа (ключ, значение).

Попробуйте использовать функцию dict.keys(), чтобы получить ключи словаря. Передайте переменную 8host.keys() функции print().

print(8host.keys())
dict_keys([‘followers’, ‘username’, ‘online’])

Ключи возвращаются в виде итерируемого объекта класса dict_keys и отображаются в формате списка.

С помощью этой функции можно создавать запросы. К примеру, так можно просмотреть одинаковые ключи в двух словарях:

Словари 8host и jesse содержат данные о профилях пользователей.

Эти профили отличаются: первый – профиль для социальных сетей, второй – профиль для игр. Однако у них совпадают два ключа: username и online. Чтобы убедиться в этом, запустите программу, и она выдаст:

8host-blog Jesse
True False

Но этот пример продемонстрировал, что dict.keys () можно использовать для поиска общих ключей в разных словарях (особенно в больших словарях). Конечно, можно улучшить программу и сделать вывод более удобным для чтения.

Функция dict.values() используется аналогичным образом и возвращает значения заданного словаря. Например:

Методы keys() и values() возвращают неотсортированные ключи или значения словаря 8host в виде объектов dict_keys и dict_values соответственно.

Чтобы запросить все элементы словаря, используйте функцию items():

print(8host.items())
dict_items([(‘online’, True), (‘username’, ‘8host-blog’), (‘followers’, 987)])

Эта функция возвращает объект dict_items, который состоит из пар (ключ, значение), представленных в виде кортежей.

Возвращенные списки можно итерировать с помощью цикла for. К примеру, так можно вывести каждый ключ и значение заданного словаря в более удобном для чтения формате:

for key, value in 8host.items():
print(key, ‘is the key for the value’, value)
online is the key for the value True
followers is the key for the value 987
username is the key for the value 8host-blog

Цикл for выполнил итерацию списков ключей и значений и вывел результат построчно.

Редактирование словарей

Словари являются изменяемым типом данных, потому их можно редактировать. В данном разделе вы узнаете, как добавлять и удалять элементы словарей.

Добавление и изменение элементов словарей

Для добавления элементов используется такой синтаксис:

Попробуйте добавить в словарь новую пару. Например:

Как видите, в словаре появилась новая пара ‘Drew’: ‘iam-drew’.

Этот же синтаксис можно использовать для изменения значений, присвоенных ключам. Для этого нужно сослаться на требуемый ключ и передать ему новое значение.

Давайте рассмотрим словарь drew, который содержит данные об одном из пользователей этой сети. Предположим, сегодня количество его подписчиков заметно увеличилось, потому нужно обновить значение его ключа ‘followers’. Чтобы убедиться, что значение было изменено, используйте функцию print().

Как видите, значение ключа followers было изменено.

Этот метод позволяет добавлять данные в словарь путём пользовательского ввода. Создайте простую программу для командной строки, usernames.py, которая позволит пользователям добавлять данные в словарь.

# Определить исходный словарь
usernames = <'8host': '8host-blog', 'Jamie': 'jamie54'>
# Добавить цикл while
while True:
# Запросить имя
print(‘Enter a name:’)
# Присвоить его переменной
name = input()
# Проверить, есть ли такое имя в словаре и вывести результат
if name in usernames:
print(usernames[name] + ‘ is the username of ‘ + name)
# Если имени нет…
else:
# Вывести на экран
print(‘I don\’t have ‘ + name + ‘\’s username, what is it?’)
# Добавить имя пользователя для такого имени
username = input()
# Присвоить имя пользователя ключу
usernames[name] = username
# Сообщить об обновлении данных
print(‘Data updated.’)

Запустите программу с помощью командной строки:

Она выведен на экран:

Enter a name:
8host
8host-blog is the username of 8hosts
Enter a name:
Jesse
I don’t have Jesse’s username, what is it?
Jesse
Data updated.
Enter a name:

Чтобы остановить программу, нажмите CTRL + C.

Как видите, словари можно редактировать в интерактивном режиме. Что касается только что рассмотренной программы, то после того, как вы нажмёте CTRL + C, все новые данные будут утрачены, поскольку в программе не настроены операции чтения и записи.

Также редактировать словари можно с помощью функции dict.update().

Попробуйте добавить в словарь jesse ключ ‘followers’ и присвоить ему целое число с помощью jesse.update(). Чтобы отобразить словарь, используйте print().

Метод dict.update() позволяет также изменять значения ключей.

Попробуйте изменить значение ключа online в словаре 8host:

Строка 8host.update(<‘online’: False>) ссылается на ключ ‘online’ и изменяет его значение True на False. Функция print() позволяет проверить результат.

Удаление элементов словарей

Чтобы удалить элемент из словаря, используйте синтаксис:

Вернёмся к словарю jesse и попробуем удалить из него строку ‘points’.

Чтобы очистить словарь, используйте функцию dict.clear(). Она сохранит словарь на случай, если он пригодится в дальнейшей работе, но удалит все его элементы.

Попробуйте удалить все элементы jesse:

Как видите, в словаре не осталось ни одной пары.

Чтобы удалить словарь, используйте:

del jesse
print(jesse)

Если вы попробуете отобразить несуществующий словарь, на экране появится ошибка:

NameError: name ‘jesse’ is not defined

Заключение

Теперь вы владеете основами работы со словарями. Словари состоят из пар «ключ: значение», которые расположены в случайном порядке и не индексируются.

Python dictionary find a key by value

In this Python tutorial, we will learn about the Python dictionary to find a key by value. Also, we will discuss the below examples:

  • Python dictionary find key by max value.
  • Python dictionary get Key value by index
  • Python dictionary find key using value
  • Python dictionary get key value pair
  • Python dictionary find key with maximum value
  • Python dictionary get key if value exists

Table of Contents

Python dictionary find a key by value

  • Here we can see how to get the key by value in Python.
  • We can perform this task by various methods, Here is the list of some that we can use.
    • By using list.index()
    • By using dict.items() method
    • By using list comprehension method

    By using list.index() method

    The index method always returns the index position in a list or dictionary.

    Source Code:

    Here is the Screenshot of the following given code

    Python dictionary find a key by value

    By using dict.items() method

    This method returns a dictionary view object that displays the list of a dictionary in the key-value pair form.

    Example:

    Execution:

    Python dictionary find a key by value method

    By using list comprehension method

    In Python to get the key with the maximum value, we can use the list comprehension method. This method will help the user to execute each element along with the for loop to iterate each item.

    Example:

    Output:

    Python dictionary find a key by value

    Python dictionary find key by max value

    • Let us see how to find the key by the maximum value.
    • By using the max() function we will find the key with maximum value in Dictionary.
    • To do this task first we will initialize a dictionary and assign them a key-value pairs element. Now use a max() function to get the key with maximum value.

    Example:

    Here is the implementation of the following given code

    Python dictionary find key by max value

    Another example to get the key with max value

    By using the itemgetter() function and operator module we can easily get the key. The itemgetter() function returns an object that collects an item from its operand using the operator module.

    Let’s take an example and check how to get the key by using the itemgetter() function.

    Here is the Screenshot of the following given code

    Python dictionary find key by max value itemgetter

    By using lambda function

    In Python, the lambda function did not need any name, they are nameless. They are used to declare a one-line function. In this example, you just need to give the function a value and then provide an expression.

    Example:

    In this example, we have to check how to find a key with maximum value using the lambda function

    Screenshot:

    Python dictionary find key by max value lambda function

    Python dictionary get key value by index

    • Let us see how to get a key-value pair by index in the dictionary.
    • To perform this task we can use the enumerator method. This is an in-built function in Python that allows the user to check how many iterations have occurred. This method can be used directly for loops and convert them into a list.
    • Let’s take an example and check how to get key-value pair by index.

    Here is the execution of the following given code

    Python dictionary get key value by index

    Another example to check how to get key-value index by using dict() method

    Source Code:

    Here is the Output of the following given code

    Python dictionary get key value by index method

    Python dictionary find key using value

    In Python to find a key using the value, we can collect the key from a value by comparing all the values and get the specific key. In this example, we can use dict.items() method.

    Example:

    Let’s take an example and check how to find a key by using the value.

    Here is the Screenshot of the following given code

    Python dictionary find key using value

    Python dictionary get key value pair

    • To get key-value pair in the dictionary we can easily use the enumerator method.
    • This method helps the user to access the named index of the position of the key-value element in the dictionary.

    Example:

    Here is the implementation of the following given code

    Python dictionary get key value pair

    Another example to check how to get key value pair

    To perform this particular task we can easily use the list comprehension method. This method returns the elements in the form of key-value pairs and it will display the result as tuples of key and value in the list.

    Example:

    Here is the Screenshot of the following given code

    Python dictionary get key value pair method

    Python dictionary find key with maximum value

    To find the key with the maximum value we can easily use the function values() and keys().

    Here is the execution of the following given code

    Python dictionary find key with maximum value

    Python dictionary get key if value exist

    • Let us see how to get a key if the value exists in dictionary.

    Python dictionary get key if value exist

    You may also like reading the following articles.

    In this Python tutorial, we have learned about the Python dictionary to find a key by value. Also, we have also discussed the below examples:

    • Python dictionary find key by max value.
    • Python dictionary get Key value by index
    • Python dictionary find key using value
    • Python dictionary get key value pair
    • Python dictionary find key with maximum value

    Fewlines4Biju Bijay

    I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *