I’m new to Python dictionaries. I’m making a simple program that has a dictionary that includes four names as keys and the respective ages as values. What I’m trying to do is that if the user enters the a name, the program checks if it’s in the dictionary and if it is, it should show the information about that name.
This is what I have so far:
def main():
people = {
"Austin" : 25,
"Martin" : 30,
"Fred" : 21,
"Saul" : 50,
}
entry = input("Write the name of the person whose age you'd like to know, or write 'ALL' to see all names and ages: ")
if entry == "ALL":
for key, value in people.items():
print ("Name: " + key)
print ("Age: " + str(value) + "n")
elif people.insert(entry) == True:
print ("It works")
main()
I tried searching through the dictionary using .index()
as I know it’s used in lists but it didn’t work. I also tried checking this post but I didn’t find it useful.
I need to know if there is any function that can do this.
Hello I am trying to find the values in a dictionary using they keys which is a 2 element tuple.
For example any basic dictionary would look like this:
dict = {'dd':1, 'qq':2, 'rr':3}
So if I would like to find the value of ‘dd’ I would simply do:
>>>dict['dd']
1
but what if I had a dictionary who’s keys were 2 element tuples:
dict = {('dd', 'ee'):1, ('qq', 'bb'):2, ('rr', 'nn'):3}
Then how can I find the value of ‘dd’ or ‘rr’
asked Dec 9, 2013 at 1:09
1
You aren’t using the dictionary properly. The keys in the dictionary should be in the form that you want to look them up. So unless you are looking up values by tuple ('dd', 'ee')
you should separate out those keys.
If you are forced to start with that dict structure then you can transform into the desired dict using this:
d1 = {('dd', 'ee'):1, ('qq', 'bb'):2, ('rr', 'nn'):3}
# creates {'dd': 1, 'ee': 1, 'qq': 2, 'bb': 2, 'rr': 3, 'nn': 3}
d2 = {x:v for k, v in d1.items() for x in k}
answered Dec 9, 2013 at 1:12
bcorsobcorso
45.2k10 gold badges63 silver badges75 bronze badges
You need to revert to a linear search
>>> D = {('dd', 'ee'):1, ('qq', 'bb'):2, ('rr', 'nn'):3}
>>> next(D[k] for k in D if 'dd' in k)
1
If you need to do more than one lookup, it’s worth building a helper dict as @bcorso suggests
having said that. dict
is probably the wrong datastructure for whatever problem you are trying to solve
answered Dec 9, 2013 at 1:11
John La RooyJohn La Rooy
293k53 gold badges364 silver badges501 bronze badges
2
Use a list comprehension:
>>> d={('dd', 'ee'):1, ('qq', 'bb'):2, ('rr', 'nn'):3, ('kk','rr'):4}
>>> [(t,d[t]) for t in d if 'rr' in t]
[(('kk', 'rr'), 4), (('rr', 'nn'), 3)]
answered Dec 9, 2013 at 1:29
dawgdawg
97.3k23 gold badges129 silver badges205 bronze badges
In this Python tutorial, we will study the implementation of Python Dictionary Search by value. Here we will see how to search for a value in Dictionary using some examples in python.
In Python, dictionaries are built-in data structure that stores key-value pairs. The keys in a dictionary must be unique, while the values can be of any data type.
There are a few different ways to get the key by value in a Python dictionary, depending on your specific use case.
- Using the items()method
- Using the list comprehension
- Using the index() method
- Using the filter() and lambda function
Method-1: Using the items() method
To get the key by value in a python dictionary is using the items() method and a for loop, items() method returns a view object that contains the key-value pairs of the dictionary, as tuples in a list.
# This code creates a dictionary called "countries" that contains the keys "USA", "Germany", and "France"
# and the respective values 56, 25, and 78.
countries = {'USA': 56, 'Germany': 25,'France':78}
# The for loop iterates through the items in the dictionary, where "key" represents the key of each item
# and "value" represents the value of each item.
for key, value in countries.items():
# The if statement checks if the value of each item is equal to 56.
if value == 56:
# If the value is equal to 56, the key of that item is printed.
print(key)
The above code outputs the USA as it is the key which has a value of 56.
Read: Python dictionary key error
Method 2: Using the list comprehension
This method iterates over the key-value pairs in the dictionary and uses a list comprehension to find the first key whose associated value is equal to the value you’re looking for.
# This code creates a dictionary called "my_dictionary" that contains keys and values
# representing countries and their respective values.
my_dictionary = {'Newzealand': 567,
'United Kingdom' : 456,
'China': 945,
'Japan': 845
}
# The variable new_val is set to 456
new_val = 456
# A list comprehension is used to iterate through the items in the dictionary and check if the value of each item is equal to new_val.
# If the value is equal to new_val, the key of that item is added to the list.
result=[new_k for new_k in my_dictionary.items() if new_k[1] == new_val][0][0]
# The result is printed
print(result)
The code outputs “United Kingdom” as it is the key which have value 456.
Read: Python Dictionary Count + Examples
Method-3: Using the index() method
The index() method is a built-in method in Python that is used to find the index of an element in a list. It takes a single argument, which is the element you want to find the index of and returns the index of the first occurrence of that element in the list.
# This code creates a dictionary called "my_dictionary" that contains keys and values
# representing countries and their respective values.
my_dictionary = {'Newzealand': 567,
'United Kingdom' : 456,
'China': 945,
'Japan': 845
}
# Get the values from the dictionary as a list
values = list(my_dictionary.values())
# The variable new_val is set to 456
new_val = 456
# Find the index of the value in the list
index = values.index(new_val)
# Get the key from the dictionary using the index
result = list(my_dictionary.keys())[index]
# The result is printed
print(result)
The above code outputs “United Kingdom” as it is the key which has value 456 but uses the index() method of the list.
Read: Python Dictionary duplicate keys
Method-4: Using the filter() and lambda function
The lambda function is a small anonymous function that can be used to perform a certain operation, and the filter() function is used to filter a sequence of elements based on a certain condition.
# my_dictionary is a dictionary that contains keys as countries and values as their population
my_dictionary = {'Newzealand': 567,
'United Kingdom' : 456,
'China': 945,
'Japan': 845
}
# new_val is the population value for which we want to find the corresponding country
new_val = 456
# Using lambda and filter() functions to filter the items of the dictionary
# and only the items with the value of new_val are returned
result = list(filter(lambda x: x[1] == new_val, my_dictionary.items()))[0][0]
# The result is printed
print(result)
The above code outputs “United Kingdom” as it is the key that has value 456 but uses the filter() and lambda function.
You may also like to read the following Python tutorials.
- Python Dictionary of sets
- Python dictionary contains + examples
- Python convert dictionary to list
- Python dictionary filter + Examples
In this Python tutorial, we have covered how to get a key using the value of the dictionary by following the below methods.
- Python Dictionary Search by value using the items() method
- Python Dictionary Search by value using the list comprehension
- Python Dictionary Search by value using the index() method
- Python Dictionary Search by value using the filter() and lambda function
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
Синтаксис:
Параметры:
key
– ключ словаря
Возвращаемое значение:
- элемент словаря, соответствующий ключу
key
Описание:
Операция dict[key]
вернет элемент словаря dict
с ключом key
. Операция вызывает исключение KeyError
, если ключ key
отсутствует в словаре.
Если подкласс dict
определяет метод __missing__()
и ключ отсутствует, операция d[key]
вызывает этот метод с ключом key
в качестве аргумента. Затем операция d[key]
возвращает или вызывает все, что было возвращено или вызвано вызовом __missing__(key)
. Никакие другие операции или методы не вызывают __missing__()
. Если __missing__()
не определен, то возникает KeyError
.
__missing__()
должен быть методом, он не может быть переменной экземпляра.
>>> class Counter(dict): ... def __missing__(self, key): ... return 0 >>> c = Counter() >>> c['red'] 0 >>> c['red'] += 1 >>> c['red'] 1
В приведенном выше примере показана часть реализации collections.Counter
.
Примеры извлечения значения ключей словаря:
>>> x = {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> x['two'] # 2 >>> x['four'] # 4 >>> x['ten'] # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # KeyError: 'ten'
В этом посте будет обсуждаться, как искать значение для данного ключа в списке словарей в Python.
1. Использование выражения генератора
Простое решение — использовать выражение генератора. Это приведет к простому коду ниже:
if __name__ == ‘__main__’: dicts = [ {“lang”: “Java”, “version”: “14”}, {“lang”: “Python”, “version”: “3.8”}, {“lang”: “C++”, “version”: “17”}, ] key = “lang” val = “Python” d = next((d for d in dicts if d.get(key) == val), None) print(d) # {‘lang’: ‘Python’, ‘version’: ‘3.8’} |
Скачать Выполнить код
2. Использование filter()
функция
Другой способ поиска в списке словарей — использование filter()
функция в Python 3.
if __name__ == ‘__main__’: dicts = [ {“lang”: “Java”, “version”: “14”}, {“lang”: “Python”, “version”: “3.8”}, {“lang”: “C++”, “version”: “17”}, ] key = “lang” val = “Python” d = next(filter(lambda d: d.get(key) == val, dicts), None) print(d) # {‘lang’: ‘Python’, ‘version’: ‘3.8’} |
Скачать Выполнить код
Это все о поиске значения в списке словарей в Python.
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂