Given your data structure:

>>> [item for item in accounts if item.get('id')==2]
[{'title': 'Gow to get this one?', 'id': 2}]

If item does not exist:

>>> [item for item in accounts if item.get('id')==10]
[]

That being said, if you have opportunity to do so, you might rethink your datastucture:

accounts = {
    1: {
        'title': 'Example Account 1'
    },
    2: {
        'title': 'Gow to get this one?'
    },
    3: {
        'title': 'Example Account 3'
    }
}

You might then be able to access you data directly by indexing their id or using get() depending how you want to deal with non-existent keys.

>>> accounts[2]
{'title': 'Gow to get this one?'}

>>> accounts[10]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 10

>>> accounts.get(2)
{'title': 'Gow to get this one?'}
>>> accounts.get(10)
# None
Answer from Sylvain Leroux on Stack Overflow
🌐
YouTube
youtube.com › codelink
python find object in list with key value - YouTube
Instantly Download or Run the code at https://codegive.com certainly! in python, you often need to search for objects within a list based on certain criteri...
Published   March 4, 2024
Views   17
Discussions

Retrieve element of object from list based on object key in Python - Stack Overflow
Just wondering if there is a more elegant way to retrieve a value from a specific object in a list based on if the object contains a particular value or if I have to write something to traverse the... More on stackoverflow.com
🌐 stackoverflow.com
Get a key from a dictionary of lists by value of one of list's items
I wouldn't complicate things too much. Iterate over the dictionary, then see if the wanted value is in the list. Something like this: wanted_item = "value2" for key, value in d.items(): if wanted_item in value: print(key) break More on reddit.com
🌐 r/learnpython
9
1
May 1, 2022
python - What is the best way to get the objects from a list of keys? - Stack Overflow
I want to pull all the objects from my list of their keys. More on stackoverflow.com
🌐 stackoverflow.com
python - Find object in list that has attribute equal to some value (that meets any condition) - Stack Overflow
I've got a list of objects. I want to find one (first or whatever) object in this list that has an attribute (or method result - whatever) equal to value. What's the best way to find it? Here's a t... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Bobby Hadz
bobbyhadz.com › blog › python-find-object-in-list-of-objects
Find object(s) in a List of objects in Python | bobbyhadz
The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value. The lambda function we passed to the filter() function gets called ...
🌐
Reddit
reddit.com › r/learnpython › get a key from a dictionary of lists by value of one of list's items
r/learnpython on Reddit: Get a key from a dictionary of lists by value of one of list's items
May 1, 2022 -

The title's confusing, but hear me out. I have a dictionary set up like this:

{
    "key1": ["value1", "value2"],
    "key2": ["value3", "value4"],
    etc.
}

Is there a way to retrieve a specific key by specifying only a single value from its associated list, i.e. get "key1" by specifying just "value2"? Every single key and value in the entire structure is unique.

So far, I've found this Stack Overflow article which explains how to look up keys by value:

mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])
# Prints george

...But it only works with flat dictionaries where values are just strings, not lists like in my case. I also could write a function that creates a new dictionary from the original one by manually iterating over it and skipping the unneeded values:

def invertDict(self, dict):
    newDict = {}
    for key, val in dict:
        newVal = str(val[1])
        newDict[newVal] = key
    return newDict

I also could just manually declare a dictionary where keys and values are reversed:

{
    "value2": "key1",
    "value4": "key2",
    etc.
}

But I only need to look it up once in the entire project, and it feels like defining a new dictionary, let alone a new function, just for one line is wasteful. There must be an elegant, pythonic way of doing this in one line, like it often is with Python, but so far I couldn't think of one. Any suggestions?

Top answer
1 of 2
2
I wouldn't complicate things too much. Iterate over the dictionary, then see if the wanted value is in the list. Something like this: wanted_item = "value2" for key, value in d.items(): if wanted_item in value: print(key) break
2 of 2
2
Is there a way to retrieve a specific key by specifying only a single value from its associated list, i.e. get "key1" by specifying just "value2"? Every single key and value in the entire structure is unique. Stop worrying about finding some specific Python solution and first solve the problem yourself. How would you do this if I gave you a printed dictionary? If I said: "tell me the key that has the item 'item1'", how would you go about it? Pretend you're having to explain this to a kindergartener who has never heard of Python, or seven-eggs-short-of-a-dozen Steve from work who browses Facebook all day instead of getting anything done? Now write those steps down. Convert those to comments. Now translate them to Python. For each key:value pair in the haystack search in the value list for the needle If the needle exists, return the key You are confusing yourself by looking at the forest instead of the trees. You don't need to solve "search a dictionary of lists for a value that might be in one of the lists and if so return the key associated with that list", you just need to solve "loop through a dictionary", "search a list", "execute and if-statement", and "return a value". Also, forget you ever saw that SO article and never, ever, ever write code like that.
🌐
GeeksforGeeks
geeksforgeeks.org › python-extract-keys-value-if-key-present-in-list-and-dictionary
Extract Key's Value, if Key Present in List and Dictionary - Python - GeeksforGeeks
February 12, 2025 - Given a list, dictionary and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary.
🌐
GeeksforGeeks
geeksforgeeks.org › python-get-values-of-particular-key-in-list-of-dictionaries
Get Values of Particular Key in List of Dictionaries - Python - GeeksforGeeks
January 28, 2025 - For example, we are having a dictionary d = {'a': 1,'b': {'a': 2, 'c': 3},'d': [{'a': 4}, {'a': 5}]} we need to to extract values from it. so that output becomes [1, 5, 4, 2]. Using a StackWe can manually manage a stac ... In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, we’ll explore different ways to filter a list of dictionaries by key from the most efficient to the least.Using List Comprehension List comprehension is a concise
🌐
Note.nkmk.me
note.nkmk.me › home › python
Get a Value from a Dictionary by Key in Python | note.nkmk.me
April 23, 2025 - d = {'key1': 1, 'key2': 2, 'key3': 3} print(list(d.values())) # [1, 2, 3] ... In Python, you can get a value from a dictionary by specifying the key like dict[key].
Find elsewhere
🌐
Finxter
blog.finxter.com › python-get-list-of-values-from-list-of-keys
Python Get List of Values from List of Keys – Be on the Right Side of Change
August 21, 2021 - d = {'alice': 18, 'bob': 24, 'carl': 32} keys = ['carl', 'bob'] result = [] for key in keys: result.append(d[key]) print(result) # [32, 24] This is the most common form used by beginners who are not yet familiar with list comprehension. However, although it’s not the most concise solution, I’d still consider it Pythonic due to its readability and simplicity.
🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.6 documentation
Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
🌐
EyeHunts
tutorial.eyehunts.com › home › python find object in list | example code
Python find object in list | Example code - Tutorial - By EyeHunts
June 13, 2022 - Python finds the object in the given list that has an attribute (or method result - whatever) equal to value. The naive loop-break on...
🌐
GeeksforGeeks
geeksforgeeks.org › searching-a-list-of-objects-in-python
Searching a list of objects in Python | GeeksforGeeks
December 27, 2023 - A simple approach is to do a linear search, that is Start from the leftmost element of the list and one by one compare x with each element of the list.If x matches with an element, return True.If x doesn’t match with any of the e
🌐
Python.org
discuss.python.org › ideas
Add safe `.get` method to List - Ideas - Discussions on Python.org
August 29, 2023 - To access an item in a dictionary, you use indexing: d["some_key"]. However, if the key doesn’t exist in the dictionary, a KeyError is raised. To avoid this, you can use .get and pass in a default value to return instead: d.get("some_key", "default value"). Lists don’t have such a method ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Extract Specific Key Values from a List of Dictionaries in Python | note.nkmk.me
May 14, 2023 - Load, parse, serialize JSON files and strings in Python · Note that a list of dictionaries can be converted to pandas.DataFrame. pandas: Convert a list of dictionaries to DataFrame with json_normalize · Use list comprehension in combination with the get() method of dictionaries. l = [ {'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20}, {'Name': 'Charlie', 'Age': 30, 'Point': 70}, ] l_name = [d.get('Name') for d in l] print(l_name) # ['Alice', 'Bob', 'Charlie'] l_age = [d.get('Age') for d in l] print(l_age) # [40, 20, 30] l_point = [d.get('Point') for d in l] print(l_point) # [80, None, 70]