Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to convert variables into dictionary entries

Suppose you have a program like this:

Spring = 1
Summer = 2
Fall = 3
Winter = 4

Let us suppose you desire to create a dictionary from these variables. Recall that a dictionary is an unordered collection of items that are stored as key-value pairs. The keys are used to identify each item within the dictionary, while the values represent the actual data associated with each key. Dictionaries are particularly useful because they allow you to quickly look up specific data by simply referencing its key. In our case, we wish to create a dictionary like:

{'Spring': 1, 'Summer': 2, 'Fall': 3, 'Winter': 4}
Convert Python variables into a Python dictionary

One way to do this is to individually create the dictionary entries:

seasons_to_vals = {}
seasons_to_vals['Spring'] = 1
seasons_to_vals['Summer'] = 2
seasons_to_vals['Fall'] = 3
seasons_to_vals['Winter'] = 4

This is not aesthetically very pleasing.

Method 1: Python variables to dict using a for loop

A better way to convert variables to a dictionary is to create a list of variables, loop through this list, and assign values to your dictionary using the eval() function applied on the variables.

Spring = 1
Summer = 2
Fall = 3
Winter = 4

seasons_to_vals = {}

seasons = ['Spring','Summer','Fall','Winter']
for s in seasons:
  seasons_to_vals[s] = eval(s)

print(seasons_to_vals)

The output is:

{'Spring': 1, 'Summer': 2, 'Fall': 3, 'Winter': 4}

as desired. Note that it is important to create/initialize the dictionary to an empty dictionary first before creating the mappings.

Method 2: Python variables to dict using a list comprehension

A second approach is to use a list comprehension. This works as follows:

Spring = 1
Summer = 2
Fall = 3
Winter = 4

seasons = ['Spring','Summer','Fall','Winter']
values = map(lambda x: eval(x), seasons)

seasons_to_vals = {key: value for (key, value) in zip(seasons,values)}

print(seasons_to_vals)

In the above program, we have a list of seasons as before. We create a parallel list of values by using a python map function over the eval applied over each element of the seasons list. Next, we use list comprehension syntax to create mappings of keys and values by pairing corresponding elements of seasons and values using a zip function. The output is as before:

{'Spring': 1, 'Summer': 2, 'Fall': 3, 'Winter': 4}

List comprehension thus allows you to quickly create dictionaries from multiple variables in one line of code instead of writing out each individual line of code for each variable separately.

Python thus provides programmers with incredibly abstractive ways to manage your variables - by helping you convert them to dictionaries! This can make code more readable and manageable since all related information is grouped together under one structure. In addition, by using list comprehensions, creating dictionaries from multiple variables can be done quickly and easily in just one line of code! If you're looking for an efficient way to store and access your data, converting your variables into dictionaries might be just what you need!

Now that you have figured out how to convert variables into a Python dictionary, learn how to do the reverse, i.e., how to unpack a dictionary into individual variables!

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

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.