Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dictionary assignment using map and lambda

I was just curious to know if the following loop is doable with the map() rather than using for loop ? If yes please be kind enough to show how ? or what's the most efficient way to do the following ?

f = open('sample_list.txt').read().split('\n')

val =   lambda x: re.match('[a-zA-z0-9]+',x).group() if x else None

for line in f:
    if line.find('XYZ') == -1:
        dict[val(line)]=0
    else:
        dict[val(line)]=1

This program reads a file formatted as :

ABCD XYZ 
DEFG ABC

then creates a dicionary with first word as KEY and if the second value is XYZ then it will assign a value of 1 else 0.

i.e dict will be :

{'ABCD': 1, 'DEFG': 0}

UPDATE :

I timed the approaches suggested by @shx2 and @arekolek dictionary comprehension is faster, and @arekolek's approach is way faster than anything as it doesn't use the val() lambda function i declared.

the code :

def a():
    return {
    val(line) : 0 if line.find('XYZ') == -1 else 1
    for line in f
    }

def b():
    return dict(map(lambda x: (x[0], int(x[1] == 'XYZ')), map(str.split, f)))

def c():
    return {k: int(v == 'XYZ') for k, v in map(str.split, f)}

print 'a='+timeit.timeit(a)
print 'b='+timeit.timeit(b)
print 'c='+timeit.timeit(c)

result :

a = 13.7737597283
b = 6.82668938135
c = 3.98859187269

Thanks both for showing this :)

like image 800
CYAN CEVI Avatar asked Jun 27 '16 09:06

CYAN CEVI


People also ask

Can I use map on dictionary Python?

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. map() returns a map object (an iterator), which we can use in other parts of our program.

How do you use lambda and map in Python?

To work with map(), the lambda should have one parameter in, representing one element from the source list. Choose a suitable name for the parameter, like n for a list of numbers, s for a list of strings. The result of map() is an "iterable" map object which mostly works like a list, but it does not print.

How does lambda and map functions work in Python?

Using lambda() Function with map() The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.

How do I iterate over a map object in Python?

Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc. using their factory functions.


Video Answer


2 Answers

Better to use dict comprehension than map.

Can be done like this:

my_dict = {
    val(line) : 0 if line.find('XYZ') == -1 else 1
    for line in f
}

Some notes and improvements:

  1. dict is not a good variable name in python
  2. Alternatives to the complicated expression 0 if line.find('XYZ') == -1 else 1:
    • int(line.find('XYZ') != -1) (converting bool to int)
    • if you can leave the values as bools: line.find('XYZ') != -1
    • 'XYZ' in line (credit: @JonClements)
like image 82
shx2 Avatar answered Oct 03 '22 18:10

shx2


With a lambda:

dict(map(lambda x: (x[0], int(x[1] == 'XYZ')), map(str.split, f)))

Or:

dict(map(lambda k, v: (k, int(v == 'XYZ')), *map(str.split, f)))

Dictionary comprehension:

{k: int(v == 'XYZ') for k, v in map(str.split, f)}
like image 41
arekolek Avatar answered Oct 03 '22 18:10

arekolek