简体   繁体   中英

How to use list extend() with map function on a dictionary

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM