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 OverflowGiven 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
The other answers are very old. The best way is with next().
next(account for account in accounts if account['id'] == 2)
See https://stackoverflow.com/a/9868665/1812732
Retrieve element of object from list based on object key in Python - Stack Overflow
Get a key from a dictionary of lists by value of one of list's items
python - What is the best way to get the objects from a list of keys? - Stack Overflow
python - Find object in list that has attribute equal to some value (that meets any condition) - Stack Overflow
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 newDictI 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?
According to documentation db.get may accept list of keys and fetch them in a single batch, which will be much faster.
list_of_objects = db.get(list_of_keys)
Not familiar with your specific application (specifically the db.get) but you may want to consider a list comprehension.
list_of_objs = [db.get(obj.key) for obj in list_of_keys]
next((x for x in test_list if x.value == value), None)
This gets the first item from the list that matches the condition, and returns None if no item matches. It's my preferred single-expression form.
However,
for x in test_list:
if x.value == value:
print("i found it!")
break
The naive loop-break version, is perfectly Pythonic -- it's concise, clear, and efficient. To make it match the behavior of the one-liner:
for x in test_list:
if x.value == value:
print("i found it!")
break
else:
x = None
This will assign None to x if you don't break out of the loop.
A simple example: We have the following array
li = [{"id":1,"name":"ronaldo"},{"id":2,"name":"messi"}]
Now, we want to find the object in the array that has id equal to 1
- Use method
nextwith list comprehension
next(x for x in li if x["id"] == 1 )
- Use list comprehension and return first item
[x for x in li if x["id"] == 1 ][0]
- Custom Function
def find(arr , id):
for x in arr:
if x["id"] == id:
return x
find(li , 1)
Output all the above methods is {'id': 1, 'name': 'ronaldo'}
my_item = next((item for item in my_list if item['id'] == my_unique_id), None)
This iterates through the list until it finds the first item matching my_unique_id, then stops. It doesn't store any intermediate lists in memory (by using a generator expression) or require an explicit loop. It sets my_item to None of no object is found. It's approximately the same as
for item in my_list:
if item['id'] == my_unique_id:
my_item = item
break
else:
my_item = None
else clauses on for loops are used when the loop is not ended by a break statement.
If you have to do this multiple times, you should recreate a dictionnary indexed by id with your list :
keys = [item['id'] for item in initial_list]
new_dict = dict(zip(keys, initial_list))
>>>{
'yet another id': {'id': 'yet another id', 'value': 901.20000000000005, 'title': 'last title'},
'an id': {'id': 'an id', 'value': 123.40000000000001, 'title': 'some value'},
'another id': {'id': 'another id', 'value': 567.79999999999995, 'title': 'another title'}
}
or in a one-liner way as suggested by agf :
new_dict = dict((item['id'], item) for item in initial_list)
Hey, I often need a way of find an object in a list of objects in python. What is the best way to do that with a one liner ;)
eg. a list of invoice objects.. now I need to find and return an invoice with invoice.invoice_number = 1234
Assuming your dictionaries always have a single key,value pair that you are extracting, you could use two list comprehensions:
l1 = [d.values()[0] for d in dividends]
# ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015']
l2 = [d.keys()[0] for d in dividends]
# [0.18, 0.21, 0.26, 0.31, 0.34, 0.38, 0.38, 0.38, 0.38, 0.415, 0.427]
Try:
yearslist = dictionary.keys()
dividendlist = dictionary.values()
For both keys and values:
items = dictionary.items()
Which can be used to split them as well:
yearslist, dividendlist = zip(*dictionary.items())