Home > Back-end >  Returning key-value pairs in a list of dictionaries
Returning key-value pairs in a list of dictionaries

Time:10-22

I am currently working with a list of dictionaries that is stored in rest_list variable after calling the get_rest(rest) function. I would like to return a list of dictionaries where availability == available (all of them in this case). This is the list of dictionaries in the rest_list variable.

[{'close_time': '5:00 pm',
  'open_time': '8:00 am',
  'name': 'Pizza DeVille',
  'city': 'Las Vegas',
  'availability': 'available'},
 {'close_time': '10:00 pm',
  'open_time': '9:00 am',
  'name': 'Cecil’s',
  'city': 'Philadelphia',
  'availability': 'available'}

The output of the new function should return this (example output):

[{'availability': 'available', 'close_time': '5:00 pm', 'city': 'Las Vegas', 'open_time': '8:00 am', 'name': 'Pizza DeVille'}, {'availability': 'available', 'close_time': '10:00 pm', 'city': 'Philadelphia', 'open_time': '9:00 am', 'name': 'Cecil’s'}

As you can see it seems to be grabbing the last key-value pair and returning it first and then returning to the top. I can basically get it to print in the same order that it's going in but I have no idea how I would grab the last part first, etc. and not do it in an orderly way.

def filter_rest(rest):
    rest_list = get_rest(rest) #function that gives me first code chunk above
    new_list = []
    for x in rest_list:
        new_list.append(x)
    return new_list

Lastly, the code above is missing an if statement of sorts so that the list of dictionaries returned only includes those where availability == 'available'. Any tips on including an if statement and getting the function to return in the order shown in the example ouput?

CodePudding user response:

l = [{'close_time': '5:00 pm',
      'open_time': '8:00 am',
      'name': 'Pizza DeVille',
      'city': 'Las Vegas',
      'availability': 'available'},
     {'close_time': '10:00 pm',
      'open_time': '9:00 am',
      'name': 'Cecil’s',
      'city': 'Philadelphia',
      'availability': 'available'}
     ]
keys=['availability','close_time','city','open_time','name']
l = [ {k:d[k] for k in keys} for d in l]
print(l)

CodePudding user response:

Let me improve a bit the answer from @islam abdelmoumen to fulfill the availability check:

keys = ['availability', 'close_time', 'city', 'open_time', 'name']
l = [{k: d[k] for k in keys} for d in l if d["availability"] == "available"]
print(l)

CodePudding user response:

You can try with filter

a = [{'close_time': '5:00 pm',
  'open_time': '8:00 am',
  'name': 'Pizza DeVille',
  'city': 'Las Vegas',
  'availability': 'available'},
 {'close_time': '10:00 pm',
  'open_time': '9:00 am',
  'name': 'Cecil’s',
  'city': 'Philadelphia',
  'availability': 'available'}]
print(list(filter(lambda x: x["availability"]=="available", a)))
# or 
print([b for b in a if b["availability"]=="available"])
  • Related