Showing posts with label Sample program. Show all posts
Showing posts with label Sample program. Show all posts

Sunday, 5 April 2020

Lambda in python with example

Lambda:

In the below example you can see two methods have been created and clearly explained to show how Lambda works

friends =  [
    {"name": "Ram", "age":26}, 
    {"name": "Raju", "age":30}
]

#method with for loop 
def findAge(name):
    for friend in friends:
        if(friend["name"] == name):
            return friend
    
    return f"{name} not found"

#method with Lambda expression 
def findAgeLambda(name):
    friend = next(filter(lambda x: x["name"] == name, friends))
    return friend

print(findAge("Ram"))
print(findAgeLambda("Raju"))  

Output:

{'name': 'Ram', 'age': 26}
{'name': 'Raju', 'age': 30}

list indices must be integers or slices, not str error in python

Below is an example to elaborate the error and for an better understanding.

Eg:

shops = [{
    "name": "Anand Motors",
    "cars": [
        {
            "name":"Ferrari",
            "Price": 25000
        },
        {
            "name": "Benz",
            "price": 15000
        }
    ]}  
]

The above dictionary is referred as list, when to try to access the dictionary data using string.

name = "Anand Motors"
print(shops[name])

The above code gives error.

Solution or fix:

name = "Anand Motors"
print(next(shop for shop in shops if shop["name"] == name))

The above code will fix this error.


Expense Handler Application with advance technologies

Budget Planner  One of the application developed with Ionic 4 and Python-Flask.  Ionic 4 code:  https://github.com/logeshbuiltin/Expense...