Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make map() return a dictionary

Tags:

python

I have the following function:

def heading_positions(self):
    return map(
            lambda h:
                {'{t}.{c}'.format(t=h.table_name,c=h.column_name) : h.position },
                self.heading_set.all()
            )

It gives me output like this:

[{'customer.customer_number': 0L}, {'customer.name': 2L}, ... ]

I would prefer just a single dictionary like this:

{'customer.customer_number': 0L, 'customer.name': 2L, ...

Is there a way to make map (or something similar) return just a single dictionary instead of an array of dictionaries?

like image 581
Jason Swett Avatar asked Feb 01 '11 13:02

Jason Swett


People also ask

Can map function be used for dictionary?

We can use the Python built-in function map() to apply a function to each item in an iterable (like a list or dictionary) and return a new iterator for retrieving the results.

How do you return a dictionary?

To return a dictionary, first create the dict object within the function body, assign it to a variable your_dict , and return it to the caller of the function using the keyword operation “ return your_dict “.

Does map work on dictionary Python?

Using Map in Python with DictionaryYou can define a dictionary using curly brackets. In the example below, you will use a dictionary of car names and append the names with a '_' in the end by using the map() function. You can see that a lambda function was used for this example.

What does map return in Python?

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)


1 Answers

Yes. The basic problem is that you don't create a dictionary out of single-entry dicts, but out of a a sequence of length-two sequences (key, value).

So, rather than create an independent single-entry dict with the function, create a tuple and then you can use the dict() constructor:

dict(map(lambda h: ('{t}.{c}'.format(t=h.table_name, c=h.column_name), h.position), 
         self.heading_set.all()))

Or directly use a generator or list comprehension inside the dict constructor:

dict(('{t}.{c}'.format(t=h.table_name, c=h.column_name), h.position) 
     for h in self.heading_set.all())

Or, on the latest versions (2.7, 3.1) a dictionary comprehension directly:

{'{t}.{c}'.format(t=h.table_name : c=h.column_name), h.position) 
     for h in self.heading_set.all()}
like image 167
Andrew Jaffe Avatar answered Sep 22 '22 18:09

Andrew Jaffe