Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to convert a list into (key, value) pairs in Python

Let us suppose you have a list of tuples of months and days in each month, like so:

months_and_days = [
    ('January', 31),
    ('February', 28),
    ('March', 31),
]

Let us suppose you would like to create a dictionary out of these tuples. Recall that a dictionary is a mapping of (key, value) pairs. How do we go about this?

Method 1: Use the dict() constructor

The straightforward way is as follows:

months_and_days = [
    ('January', 31),
    ('February', 28),
    ('March', 31),
]

mydict = dict(months_and_days)

print(months_and_days)
print(mydict)
Convert Python list into (key, value) pairs

The output will be:

[('January', 31), ('February', 28), ('March', 31)]
{'January': 31, 'February': 28, 'March': 31}

Note that the first line denotes the list where each element is a tuple. The second line is a dictionary of key value pairs denoted by the colon (“:”) separating the keys and values, as we wanted.

In other words, to convert a list into (key, value) pairs or a dictionary, just use the dict() constructor and create a dictionary!

If you want to learn how to convert individual variables into a dictionary instead of lists, check out our guide on converting variables to dictionary entries. To access specific elements in your newly created dictionary, you can learn how to retrieve the first key in a Python dictionary.

Method 2: Use dictionary comprehension

Our second approach uses dictionary comprehension which is a compact Python-ic way to achieve our objectives. This works as follows:

months_and_days = [
    ('January', 31),
    ('February', 28),
    ('March', 31),
]

mydict = {month: days for month, days in months_and_days}

print(months_and_days)
print(mydict)

The output will be the same as before:

[('January', 31), ('February', 28), ('March', 31)]
{'January': 31, 'February': 28, 'March': 31}

How does the above code work?

Essentially, it is doing what is called tuple unpacking. The “for months, days in months_and_days” returns each of the entries of the original list and we have unpacked it into separate variables, namely month and days. The first element of each tuple is assigned to month. The second element of each tuple is assigned to days. These are then put together as key, value pairs in “mydict”.

You can think of this as just shorthand for a traditional for loop which is our third method.

Method 3: Use a for loop

months_and_days = [
    ('January', 31),
    ('February', 28),
    ('March', 31),
]

mydict = {}
for month, days in months_and_days:
    mydict[month] = days
print(mydict)

The output will be the same as before. The comprehension in Method 2 is just a more compact and concise way of writing the loop, but both approaches create the same dictionary.

Method 4: Use a zip() function

This approach works like the following:

months_and_days = [
    ('January', 31),
    ('February', 28),
    ('March', 31),
]

months, days = zip(*months_and_days)
mydict = dict(zip(months, days))
print(mydict)

The output will be:

{'January': 31, 'February': 28, 'March': 31}

This approach demonstrates tuple unpacking and the use of Python's zip() function. The line months, days = zip(*months_and_days) uses the asterisk (*) operator to unpack the list of tuples, and zip() then transposes this data into two separate tuples: thus, months becomes ('January', 'February', 'March') and days becomes (31, 28, 31). Then, dict(zip(months, days)) takes these two sequences and creates a dictionary by pairing corresponding elements - the first element from months becomes a key paired with the first element from days as its value, and so on. The resulting dictionary mydict will be {'January': 31, 'February': 28, 'March': 31}. When this dictionary is printed, it shows all key-value pairs enclosed in curly braces. This method of dictionary creation is particularly useful when you have parallel sequences that you want to combine into key-value pairs.

Once you've created your dictionary, you might want to learn about slicing dictionaries to work with specific portions of your data.

Converting a flattened list into a dictionary

Let us suppose instead of a list of tuples, our original list was a flattened one with alternate month names and numbers. How do we convert that into a dictionary?

# Let us first flatten the list
flattened_months_and_days = ['January', 31, 'February', 28, 'March', 31]

# Create dictionary from flattened list
mydict = dict(zip(flattened_months_and_days[::2], flattened_months_and_days[1::2]))
print(mydict)

To create a dictionary from our flattened list, we use zip() with list slicing: flattened[::2] takes every second element starting from index 0 (the month names), and flattened[1::2] takes every second element starting from index 1 (the numbers of days). The dict() constructor then pairs these elements together, creating a dictionary where the month names are keys and the numbers are values, resulting in {'January': 31, 'February': 28, 'March': 31}.

This method is particularly useful when dealing with flattened data structures that alternate between keys and values. But of course you need to be careful that your list is in this format before you proceed to map it into a dictionary.

Of course if you have two lists separately organized already then it is easy to convert them into a dictionary using our zip() approach from Method 4.

Btw, as an aside, when working with lists before converting them to dictionaries, you might find it useful to know how to print lists without brackets and commas.

Finally, let us look at four practical situations where you need to convert a list of key-value tuples into a dictionary.

Database Query Results

When receiving query results from a database that returns tuples of (ID, value) pairs you might want to convert them to a dictionary:

# Database returns tuples of user_id and email
query_results = [
    (101, "john@email.com"),
    (102, "mary@email.com"),
    (103, "bob@email.com")
]
user_emails = dict(query_results)

File Processing

When parsing log files or configuration files we will need to organize key-value pairs as a dictionary:

# Log file parsing results
log_entries = [
    ("2024-01-01", "system_start"),
    ("2024-01-02", "error_detected"),
    ("2024-01-03", "system_shutdown")
]
log_dict = dict(log_entries)

​​HTTP Headers

When working with HTTP protocols, the headers come as tuples which will need to be organized as a dictionary:

# HTTP headers as tuples
headers = [
    ("Content-Type", "application/json"),
    ("Authorization", "Bearer token123"),
    ("Accept", "text/html")
]
headers_dict = dict(headers)

Environment Variables

Finally, when you are processing environment variables, such information is often available in the form of tuples that it would be useful to organize as a dictionary:

# Environment settings as tuples
env_settings = [
    ("PATH", "/usr/local/bin"),
    ("HOME", "/home/user"),
    ("LANG", "en_US.UTF-8")
]
env_dict = dict(env_settings)

In all of the above cases, using dict() directly on the list of tuples is the most efficient way to create the dictionary, as the data is already in the correct (key, value) format.

If you liked this blogpost, checkout our blogpost on how to map variables to a dictionary!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.