3

I am new to python and trying to understand how map function works

I have an input dictionary with key as a string and value as list of strings

input_dict = {'Mobile': ['Redmi', 'Samsung', 'Realme'], 
'Laptop': ['Dell', 'HP'],
'TV': ['Videocon', 'Sony'] }

I want to convert it into a list like below

['Mobile_Redmi', 'Mobile_Samsung', 'Mobile_Realme', 'Laptop_Dell', 'Laptop_HP', 'TV_Videocon', 'TV_Sony']

so I tried using map function with list extend method like below.

def mapStrings(item):
    key, value_list = item[0], item[1]  
    result = []
    for val in value_list:
        result.append(key+"_"+val)
    return result

result_list = []
result_list.extend(map(mapStrings, input_dict.items()))
print(result_list)

The above code gives me

[['Mobile_Redmi', 'Mobile_Samsung', 'Mobile_Realme'], ['Laptop_Dell', 'Laptop_HP'], ['TV_Videocon', 'TV_Sony']]

I am trying to understand why the result_list.extend() did not produce the desired output.

1 Answers1

3

extend adds all elements of an iterable to the list. In this case the elements are lists themselves, so you get a nested list. What you want is to extend the list with each list from the dict individually, something like:

result_list = []
for item in input_dict.items():
    result_list.extend(mapStrings(item))

If you really want to use map, you can use:

result_list = [item for items in map(mapStrings, input_dict.items()) for item in items]

For more ways look at How to make a flat list out of list of lists? Just note that you are not really dealing with a list of lists, but with a map object so be careful for slight differences.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    `sum(map(mapStrings, input_dict.items()), [])` is a well-known anti-pattern, it is quadratic time when you can trivially flatten an iterable of lists in linear time. Note, the `sum` function will actually throw an error if you try to do this with strings to prevent this exact thing! Basically, you shouldn't use sequence concatenation to flatten a list. Otherwise this is a good answer! – juanpa.arrivillaga Aug 16 '20 at 11:52
  • So, you could just do `[item for sublist in map(...) for item in sublist]` or `from itertools import chain` then `list(chain.from_iterable(map(...)))` – juanpa.arrivillaga Aug 16 '20 at 11:53
  • I am aware of this and considered adding a comment about it, this is why it is in the end. My main suggestion is the regular loop – Tomerikoo Aug 16 '20 at 11:54
  • But there are alternatives, you don't have to use sum to work with `map` to essentially get a flat-map operation – juanpa.arrivillaga Aug 16 '20 at 11:54
  • @juanpa.arrivillaga You are right, totally agree. Changing to a more general remark – Tomerikoo Aug 16 '20 at 11:55