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?
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.
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 “.
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.
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.)
Yes. The basic problem is that you don't create a dictionary out of single-entry dict
s, 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()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With