1

I am trying to retrieve the item from a key in select dictionaries within a list of dictionaries, where selection of the dictionary is conditional on the value of the item against multiple other keys present in the dictionaries.

E.g. For list of dictionaries, d:

d = [{a:'2.1', z:'apple', aa:'banana'}, {a:'3.6', z:'cherry', aa:'peach'}, {a:'4.7', z:'apple', aa:'banana'}, {a:'1.6', z:'apple', aa:'orange'}]

I am interested in retrieving the item against 'a' for the last dictionary in the list where 'z':'apple' and 'aa':'banana' are satisfied conditions i.e. get the item against key 'a' from d[-2] in the above example.

Is there some simple code to do this?

I have tried:

  1. Python: get a dict from a list based on something inside the dict - but not sure how to extend this to be conditional on the items against multiple keys inside the dictionaries.

  2. Slicing a dictionary - but not sure how to add the conditional aspect using Python syntax.

I expect the solution involves some sort of dictionary comprehension, but am relatively new to Python.

Any help appreciated.

techytushar
  • 673
  • 5
  • 17
PavK0791
  • 71
  • 2
  • 7

2 Answers2

1

You can use list comprehension to filter list of dictionaries by condition and take the last dictionary from satisfied cases:

dicts = [{'a':'2.1', 'z':'apple', 'aa':'banana'}, {'a':'3.6', 'z':'cherry', 'aa':'peach'}, 
         {'a':'4.7', 'z':'apple', 'aa':'banana'}, {'a':'1.6', 'z':'apple', 'aa':'orange'}]

filtered_list = [elem for elem in dicts if elem.get('z') == 'apple' and elem.get('aa') == 'banana']
if filtered_list:
    result = filtered_list[-1]
else:
    result = None
    print("There's no satisfied dictionary.")
print(result)
# {'a': '4.7', 'z': 'apple', 'aa': 'banana'}
print(result['a'])
# 4.7
Eduard Ilyasov
  • 3,268
  • 2
  • 20
  • 18
0

Iterate the reversed list, and break as soon as you find a dict satisfying the conditions:

dicts = [{'a':'2.1', 'z':'apple', 'aa':'banana'}, {'a':'3.6', 'z':'cherry', 'aa':'peach'}, 
         {'a':'4.7', 'z':'apple', 'aa':'banana'}, {'a':'1.6', 'z':'apple', 'aa':'orange'}]

for d in reversed(dicts):
    if d['z'] == 'apple' and d['aa'] == 'banana':
        break

print(d)
# {'a': '4.7', 'z': 'apple', 'aa': 'banana'}
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • 1
    What if there's no key 'aa' or 'z' in dictionary of list before you find satisfied case? And if there's no satisfied dict in list you'll get first element of list and should do additional check on that. – Eduard Ilyasov Sep 30 '19 at 06:01