简体   繁体   中英

How to assign values in lambda function in Python?

I am using lambda function to make my code optimize and faster. Below I have written some function.

a = [{"objId":"5c077187fe506f8dd3589ce6","userid":"absurana","firstName":"Null","usrRole":"Software Quality User","lastName":"Null","tiles":"Potential CFD","userType":"User"},
 {"objId":"5d9d7ce6fe506f11b275d01b","userid":"accheung","firstName":"Null","usrRole":"Software Quality User","lastName":"Null","tiles":"Potential CFD",,"userType":"User"},
 {"objId":"5d9d7ce6fe506f11b275d01b","userid":"accheung","firstName":"Null","usrRole":"Software Quality User","lastName":"Null","tiles":"Potential CFD","userType":"User"}]

def function_apply(a):
    for d in a:
        if 'userid' in d:
            d['UserId'] = d.pop('userid')
        if 'userType' in d:
            d['User Type'] = d.pop('userType')
        if 'usrRole' in d:
            d['Role'] = d.pop('usrRole')
        if 'tiles' in d:
            d['Tiles'] = d.pop('tiles')
    return a

Now I want to convert same above function in lambda using map, but getting error. How could I achieve this?

A one-liner, concise, pythonic way:

mapping = {"userid": "UserId", "userType": "User Type", "usrRole": "Role", "tiles": "Tiles"}  
def rename(x): return [{mapping.get(k, k):v for (k,v) in d.items()} for d in x]

Please note that the usage of lambda is not providing any computation time gain. Regarding readability, a standard def is the most expected call for a function definition.

>>> rename(a)

[{'objId': '5c077187fe506f8dd3589ce6',
  'UserId': 'absurana',
  'firstName': 'Null',
  'Role': 'Software Quality User',
  'lastName': 'Null',
  'Tiles': 'Potential CFD',
  'User Type': 'User'},
 {'objId': '5d9d7ce6fe506f11b275d01b',
  'UserId': 'accheung',
  'firstName': 'Null',
  'Role': 'Software Quality User',
  'lastName': 'Null',
  'Tiles': 'Potential CFD',
  'User Type': 'User'},
 {'objId': '5d9d7ce6fe506f11b275d01b',
  'UserId': 'accheung',
  'firstName': 'Null',
  'Role': 'Software Quality User',
  'lastName': 'Null',
  'Tiles': 'Potential CFD',
  'User Type': 'User'}]

What you have now is about as efficient as you can get. If you want to make the code less repetitive , you can do something like

key_map = {
    'userid': 'UserId',
    'userType': 'User Type',
    'usrRole': 'Role',
    'tiles': 'Tiles',
}

def function_apply(a):
    for old, new in key_map.items():
        for d in a:
            if old in d:
                d[new] = d.pop(old)

You need a function that can be applied to the individual dicts, eg:

keys = [
    ('userid', 'UserId'), ('userType', 'User Type'),
    ('usrRole', 'Role'), ('tiles', 'Tiles'),
]

def rename_keys(dct):
    for old, new in keys:
        if old in dct:
            dct[new] = dct.pop(old)

This function can now be applied to the list elements in a loop:

for d in a:
    rename_keys(d)

Using map to do this, is rather pointless:

map(rename_keys, a)

itself does nothing, as the changes will only become effective once the iterator is consumed. So you would have to do something like:

list(map(rename_keys, a))
# or
for _ in map(rename_keys, a): pass

Which illustrates why you shouldn't do it: one creates a spurious in-memory list, the other ends up with a loop anyway. If you don't use the return values of the function, don't use it in map or a comprehension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM