pythonlambdapyvmomi

Python map and lambda combination gives error


I am trying the following working code

from pyVmomi import vim
mapping = []
propertyDict = {'ipv4': '192.168.2.2/24'}
for k in propertyDict:
    v = propertyDict[k]
    mapping.append(vim.KeyValue(key=k, value=v))

with map and lambda as below

mapping.append(map(lambda k: vim.KeyValue(key=k,value=propertyDict[k]), propertyDict))

but getting error as For "propertyMapping" expected type vim.KeyValue, but got list, when I used it in mapping value in the following function

if mapping:
    spec_params = vim.OvfManager.CreateImportSpecParams(entityName=vmname,
                                                         propertyMapping=mapping)

Solution

  • map function returns an iterator with several values, and not a single value.

    You should replace:

    mapping.append(map(lambda k: vim.KeyValue(key=k,value=propertyDict[k]), propertyDict))
    

    by:

    mapping.extend(map(lambda k: vim.KeyValue(key=k,value=propertyDict[k]), propertyDict))
    

    Moreover, map is rarely used in python. We prefer list comprehensions. I would propose:

    mapping.extend(vim.KeyValue(key=k, value=v) for k,v in propertyDict.items())