Search code examples
pythondictionarydictionary-comprehension

How to use map() with dictionary comprehension in Python


I am trying to use map() on a list of dictionaries to get a name and id only.

My input:

employees = [
   {"id": 12113, "name": "Jim", "department": "Sales"},
   {"id": 12342, "name": "Michael", "department": "Management"},
   {"id": 23312, "name": "Dwight", "department": "Sales"},
]

What I want my function to return is a dictionary where each key is the employee's name and the value is the employee's ID.

My function currently contains what is below but isn't returning values, only: <map object at 0x7f3b0bb6d460>, <map object at 0x7f78e7242670>.

My code:

def name_id(employees):

   name_and_ids = [{map(('name', 'id'), emp) for emp in employees}]
   print(list(name_id)) ### to see if what I want is being output or not
   return name_and_ids

I am calling my function with:

  print(f"Name and ids: {name_id(employees)}")

I am fairly new to python and am getting confused with comprehensions in general, whether list or dictionary comprehensions. I did see you can use dict and/or zip but would like to learn something new with map().

Any advice/help to push me in the right direction of getting what I want would be much appreciated.


Solution

  • What I want my function to return is a dictionary where each key is the employee's name and the value is the employee's ID.

    You need a dictionary comprehension:

    result = {
        emp['name']: emp['id']
        for emp in employees
    }
    

    map is not an appropriate tool for the job, because it converts N things to N other things, whereas you need to convert N things (3 employees) into one thing (a dict). If you insist, you could use map to convert the source list into a list of key-value tuples and then apply dict to the result:

    from operator import itemgetter
    
    result = dict(
        map(itemgetter('name', 'id'), employees)
    )
    

    This style is not considered "pythonic" though.