Skip to content

Map list to dictionary Python | Example code

  • by

Using the zip( ) function or dictionary comprehension you can convert the Map list to the dictionary in Python

Dictionary comprehension syntax:

def foo(somelist):
    return {x[0]:x for x in somelist}

Example Map list to dictionary Python

A simple example code function that will return the name of a key, and the value will be the original value.

def foo(somelist):
    return {x[0]: x for x in somelist}


list1 = ["Hello", "World"]

print(foo(list1))

Output:

OR

def foo(keyfunc, values):
    return dict((keyfunc(v), v) for v in values)


print(foo(lambda a: a[0], ["hello", "world"]))

Python program to map two lists into a dictionary.

You can accomplish this with a combination of map, zip, and the dict constructor:

keys = ['red', 'green', 'blue']
values = ['#FF0000', '#008000', '#0000FF']

color_dictionary = dict(zip(keys, values))

print(color_dictionary)

Output: {‘red’: ‘#FF0000’, ‘green’: ‘#008000’, ‘blue’: ‘#0000FF’}

Do comment if you have any doubts or suggestions on this Python Map list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading